/* ============================================================
 * CRM API Ingestion section
 * Editorial visual showing data flowing into the CRM from PMSs,
 * booking engines, channel managers, plus a real code sample
 * and a list of cron jobs / webhooks. Visually lifted to match
 * the analytics + hero artifacts.
 * ============================================================ */

const { useState: useStateApi, useEffect: useEffectApi } = React;

// ────────────────────────── palette (mirrors crm-analytics) ──────────────────────────
const API_BG       = "#120912";
const API_PANEL    = "#1a0f1a";
const API_PANEL_2  = "#22142a";
const API_RULE     = "#3a1f3a";
const API_RULE_S   = "#2a172a";
const API_INK      = "#f5e6f0";
const API_MUTED    = "#a896a6";
const API_DIM      = "#7a6a78";
const API_FUCHSIA  = "#ff4d97";
const API_F_DEEP   = "#d63d80";
const API_F_LIGHT  = "#ff8fbc";
const API_PINK     = "#ff7ab8";
const API_MAGENTA  = "#c235a3";
const API_HOT      = "#ff2d7c";
const API_POS      = "#5cd0a0";
const API_BLUE     = "#7fb8ff";

const API_MONO  = "'JetBrains Mono', ui-monospace, monospace";
const API_SANS  = "'Inter', system-ui, sans-serif";

function ApiMono({ size = 11, color = API_MUTED, style = {}, children }) {
  return (
    <span style={{
      fontFamily: API_MONO,
      fontSize: size,
      color,
      letterSpacing: "0.04em",
      ...style,
    }}>{children}</span>
  );
}

function CrmApiIngestionVisual() {
  /* Animated 'recent ingest' feed for the right column */
  const baseEvents = [
    { src: "Mews",         t: "PMS",            evt: "reservation.upsert",     id: "RES-247901", ms: 38, hot: true },
    { src: "Booking.com",  t: "Channel mgr",    evt: "reservation.created",    id: "BDC-A1F2",   ms: 64, hot: false },
    { src: "Apaleo",       t: "PMS",            evt: "extras.recovered",       id: "EXT-9921",   ms: 122, hot: false },
    { src: "Cloudbeds",    t: "PMS",            evt: "guest.checked_in",       id: "GST-1820",   ms: 41, hot: true },
    { src: "Direct site",  t: "Booking engine", evt: "reservation.created",    id: "DIR-77104",  ms: 28, hot: false },
    { src: "Opera",        t: "PMS",            evt: "reservation.modified",   id: "OPR-55320",  ms: 81, hot: false },
    { src: "Mews",         t: "PMS",            evt: "reservation.cancelled",  id: "RES-247612", ms: 47, hot: false },
    { src: "SiteMinder",   t: "Channel mgr",    evt: "reservation.created",    id: "SMR-1109",   ms: 71, hot: false },
    { src: "Apaleo",       t: "PMS",            evt: "guest.checked_out",      id: "GST-1612",   ms: 33, hot: true },
    { src: "Stripe",       t: "Payments",       evt: "payment.received",       id: "PAY-AC3E",   ms: 19, hot: false },
  ];

  const [ticker, setTicker] = useStateApi(0);
  useEffectApi(() => {
    const id = setInterval(() => setTicker(x => x + 1), 1400);
    return () => clearInterval(id);
  }, []);

  /* always show 7 most recent, newest at top */
  const visible = [];
  for (let i = 0; i < 7; i++) {
    visible.push(baseEvents[(ticker + i) % baseEvents.length]);
  }

  const sources = [
    { label: "PMSs",             items: ["Mews", "Apaleo", "Cloudbeds", "Opera", "Protel", "+ 12 more"] },
    { label: "Booking engines",  items: ["Direct site", "ROIBACK", "BookingExpert", "SiteMinder", "+ custom"] },
    { label: "Channel managers", items: ["SiteMinder", "STAAH", "RoomCloud", "TravelClick", "+ custom"] },
    { label: "OTAs",             items: ["Booking.com", "Expedia", "Airbnb", "Hotelbeds", "+ all majors"] },
    { label: "Payments & ops",   items: ["Stripe", "Adyen", "Revinate", "TrustYou", "+ custom"] },
  ];

  const crons = [
    { kind: "webhook", name: "reservation.upsert",                 sub: "real-time, <100ms from PMS to CRM" },
    { kind: "webhook", name: "guest.checked_in / checked_out",     sub: "flips lifecycle stage instantly, fires journeys" },
    { kind: "cron",    name: "extras.recovery, +24h post checkout", sub: "re-pulls minibar, spa, restaurant charges that posted late" },
    { kind: "cron",    name: "consumption sweep, hourly",           sub: "reconciles board type, room moves, late check-outs" },
    { kind: "cron",    name: "historical backfill",                 sub: "bulk endpoint, up to 5,000 reservations per call" },
  ];

  const code = `curl -X POST https://guestmaker.ai/api/v1/reservations \\
  -H "Authorization: Bearer gmkr_••••••••••" \\
  -H "Content-Type: application/json" \\
  -d '{
    "reservation_id": "RES-247901",
    "source":         "pms",
    "channel":        "booking.com",
    "hotel_code":     "rev-mare",
    "check_in":       "2026-07-15",
    "check_out":      "2026-07-18",
    "status":         "confirmed",
    "amount":         743.00,
    "currency":       "EUR",
    "guests": [{
      "first_name": "Aoife", "last_name": "Daly",
      "phone":      "+353871234567",
      "language":   "en",
      "is_holder":  true
    }],
    "extras": [
      { "name": "Spa, 60min",    "amount": 95.00 },
      { "name": "Minibar",       "amount": 18.50 }
    ]
  }'`;

  return (
    <ScaleFrame nativeWidth={1216} style={{ maxWidth: 1216, margin: "0 auto" }}>
    <div style={{
      maxWidth: "var(--rail)", margin: "0 auto",
      background: API_PANEL,
      border: `1px solid ${API_RULE}`,
      borderRadius: 14,
      boxShadow: `0 30px 80px -30px rgba(0,0,0,0.7), 0 0 60px -20px ${API_FUCHSIA}25`,
      overflow: "hidden",
      position: "relative",
      color: API_INK,
      fontFamily: API_SANS,
    }}>
      {/* scoped style: scrollbar + ambient glow keyframes */}
      <style>{`
        .api-scroll { scrollbar-width: thin; scrollbar-color: ${API_RULE} transparent; }
        .api-scroll::-webkit-scrollbar { width: 6px; height: 6px; }
        .api-scroll::-webkit-scrollbar-track { background: transparent; }
        .api-scroll::-webkit-scrollbar-thumb { background: ${API_RULE}; border-radius: 3px; }
        .api-scroll::-webkit-scrollbar-thumb:hover { background: ${API_FUCHSIA}66; }
        @keyframes api-row-in {
          0%   { background: ${API_FUCHSIA}26; }
          100% { background: transparent; }
        }
        @keyframes api-pulse {
          0%, 100% { opacity: 1; transform: scale(1); }
          50%      { opacity: 0.4; transform: scale(0.7); }
        }
      `}</style>

      {/* ambient glow inside panel */}
      <div style={{
        position: "absolute", top: -120, left: "10%", width: 480, height: 480,
        background: `radial-gradient(circle, ${API_FUCHSIA}15, transparent 65%)`,
        pointerEvents: "none",
      }} />
      <div style={{
        position: "absolute", bottom: -180, right: "5%", width: 520, height: 520,
        background: `radial-gradient(circle, ${API_MAGENTA}12, transparent 65%)`,
        pointerEvents: "none",
      }} />

      {/* NOTE: an earlier attempt stacked these two-up rows at mobile. It
          removed the overflow but the dense columns then OVERLAPPED
          ("reservation.upsert" over "RES-247901", the source matrix headings
          over their own items) — fits-but-illegible, which is worse than
          clipped. This panel is a product mockup, so the whole thing is
          scaled by <ScaleFrame> at the call site instead. The minmax(0,...)
          below stays only as a defence against pathological track blowout. */}
      {/* ===== TOP: code sample + ingest feed ===== */}
      <div style={{
        display: "grid",
        gridTemplateColumns: "minmax(0, 1.15fr) minmax(0, 1fr)",
        borderBottom: `1px solid ${API_RULE_S}`,
        position: "relative",
      }}>
        {/* code column */}
        <div style={{
          padding: "22px 26px 20px",
          borderRight: `1px solid ${API_RULE_S}`,
          background: `linear-gradient(180deg, ${API_PANEL_2}40, ${API_PANEL})`,
        }}>
          <div style={{
            display: "flex", justifyContent: "space-between", alignItems: "center",
            gap: 12, flexWrap: "wrap", marginBottom: 16,
          }}>
            <div style={{ display: "inline-flex", gap: 6, flexWrap: "wrap", minWidth: 0, maxWidth: "100%" }}>
              {[
                { label: "POST /api/v1/reservations", active: true },
                { label: "/api/v1/cdp/reservations/bulk", active: false },
                { label: "/api/v1/events", active: false },
              ].map((t, i) => (
                <span key={i} style={{
                  fontFamily: API_MONO, fontSize: 10.5,
                  padding: "5px 9px", borderRadius: 6,
                  letterSpacing: "0.02em",
                  // An endpoint path is one unbreakable mono token; without this
                  // the widest pill sets the row's min-content width and the
                  // whole strip is clipped on a phone.
                  overflowWrap: "anywhere", minWidth: 0,
                  border: `1px solid ${t.active ? API_FUCHSIA + "59" : API_RULE_S}`,
                  background: t.active ? `${API_FUCHSIA}1a` : "transparent",
                  color: t.active ? API_FUCHSIA : API_DIM,
                  boxShadow: t.active ? `0 0 12px ${API_FUCHSIA}30` : "none",
                }}>{t.label}</span>
              ))}
            </div>
            <ApiMono size={10.5} color={API_DIM}>curl · Bearer gmkr_•••</ApiMono>
          </div>

          <pre className="api-scroll" style={{
            margin: 0,
            fontFamily: API_MONO, fontSize: 12.2,
            lineHeight: 1.65,
            color: API_INK,
            whiteSpace: "pre-wrap", wordBreak: "break-word",
            padding: "16px 18px",
            background: API_BG,
            border: `1px solid ${API_RULE_S}`,
            borderRadius: 10,
            maxHeight: 320, overflow: "auto",
          }}><code>{code}</code></pre>

          <div style={{
            marginTop: 14,
            display: "flex", alignItems: "center", gap: 10,
            fontFamily: API_MONO, fontSize: 10.5,
            color: API_MUTED, letterSpacing: "0.04em",
          }}>
            <span style={{
              width: 6, height: 6, borderRadius: "50%",
              background: API_POS, boxShadow: `0 0 8px ${API_POS}`,
            }} />
            <span>200 OK · upserted in 38ms · contact resolved · profile enriched</span>
          </div>
        </div>

        {/* feed column */}
        <div style={{
          padding: "22px 26px 18px",
          display: "flex", flexDirection: "column",
          background: API_PANEL,
        }}>
          <div style={{
            display: "flex", alignItems: "center", gap: 10,
            paddingBottom: 14, marginBottom: 10,
            borderBottom: `1px solid ${API_RULE_S}`,
          }}>
            <span style={{
              width: 8, height: 8, borderRadius: "50%",
              background: API_FUCHSIA,
              boxShadow: `0 0 10px ${API_FUCHSIA}`,
              animation: "api-pulse 1.4s ease-in-out infinite",
            }} />
            <ApiMono size={11} color={API_MUTED} style={{ letterSpacing: "0.12em", textTransform: "uppercase", flex: 1 }}>
              Live ingest, last 60s
            </ApiMono>
            <ApiMono size={10.5} color={API_DIM}>2,317 events</ApiMono>
          </div>

          <div style={{ flex: 1 }}>
            {visible.map((e, i) => (
              <div
                key={`${ticker}-${i}`}
                style={{
                  display: "grid",
                  gridTemplateColumns: "minmax(0, 1.1fr) minmax(0, 1.1fr) minmax(0, 1fr) minmax(0, 0.5fr)",
                  gap: 12, alignItems: "center",
                  padding: "10px 0",
                  borderBottom: i < 6 ? `1px dashed ${API_RULE_S}` : "none",
                  fontSize: 12.5,
                  opacity: 1 - i * 0.08,
                  animation: i === 0 ? "api-row-in 0.5s ease" : "none",
                }}>
                <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
                  <span style={{ color: API_INK, fontWeight: 500, fontSize: 12.5 }}>{e.src}</span>
                  <ApiMono size={9.5} color={API_DIM} style={{ letterSpacing: "0.1em", textTransform: "uppercase" }}>{e.t}</ApiMono>
                </div>
                <ApiMono size={11.5} color={e.hot ? API_FUCHSIA : API_MUTED} style={{
                  letterSpacing: "0.01em",
                  textShadow: e.hot ? `0 0 8px ${API_FUCHSIA}40` : "none",
                }}>{e.evt}</ApiMono>
                <ApiMono size={11} color={API_DIM} style={{ letterSpacing: "0.02em" }}>{e.id}</ApiMono>
                <ApiMono size={11} color={API_POS} style={{ textAlign: "right", fontVariantNumeric: "tabular-nums" }}>{e.ms}ms</ApiMono>
              </div>
            ))}
          </div>

          <div style={{
            display: "flex", justifyContent: "space-between",
            paddingTop: 12, marginTop: 10,
            borderTop: `1px solid ${API_RULE_S}`,
          }}>
            <ApiMono size={10.5} color={API_DIM}>p50 41ms · p99 280ms · 0 dropped</ApiMono>
            <ApiMono size={10.5} color={API_DIM}>EU region</ApiMono>
          </div>
        </div>
      </div>

      {/* ===== BOTTOM: source matrix + cron lanes ===== */}
      <div style={{
        display: "grid",
        gridTemplateColumns: "minmax(0, 1.4fr) minmax(0, 1fr)",
        position: "relative",
      }}>
        {/* sources column */}
        <div style={{
          padding: "22px 26px 26px",
          borderRight: `1px solid ${API_RULE_S}`,
        }}>
          <div style={{ display: "inline-flex", alignItems: "center", gap: 10, marginBottom: 18 }}>
            <span style={{ display: "inline-block", width: 14, height: 1.5, background: API_FUCHSIA, boxShadow: `0 0 6px ${API_FUCHSIA}` }} />
            <ApiMono size={11} color={API_FUCHSIA} style={{ letterSpacing: "0.16em", textTransform: "uppercase", fontWeight: 600 }}>
              Sources we ingest from
            </ApiMono>
          </div>

          <div style={{ display: "grid", gridTemplateColumns: "repeat(5, minmax(0, 1fr))", gap: 0 }}>
            {sources.map((s, i) => (
              <div key={i} style={{
                padding: "0 14px 0 0",
                borderRight: i < sources.length - 1 ? `1px solid ${API_RULE_S}` : "none",
                marginLeft: i === 0 ? 0 : 14,
              }}>
                <div style={{
                  fontSize: 13, color: API_INK, fontWeight: 600,
                  letterSpacing: "-0.005em", marginBottom: 10,
                }}>{s.label}</div>
                <ul style={{ listStyle: "none", margin: 0, padding: 0, display: "flex", flexDirection: "column", gap: 5 }}>
                  {s.items.map((it, j) => (
                    <li key={j} style={{
                      fontFamily: API_MONO, fontSize: 11.5,
                      color: it.startsWith("+") ? API_DIM : API_MUTED,
                      letterSpacing: "0.01em",
                    }}>{it}</li>
                  ))}
                </ul>
              </div>
            ))}
          </div>
        </div>

        {/* crons column */}
        <div style={{ padding: "22px 26px 26px" }}>
          <div style={{ display: "inline-flex", alignItems: "center", gap: 10, marginBottom: 18 }}>
            <span style={{ display: "inline-block", width: 14, height: 1.5, background: API_FUCHSIA, boxShadow: `0 0 6px ${API_FUCHSIA}` }} />
            <ApiMono size={11} color={API_FUCHSIA} style={{ letterSpacing: "0.16em", textTransform: "uppercase", fontWeight: 600 }}>
              Webhooks & crons
            </ApiMono>
          </div>

          <ul style={{ listStyle: "none", margin: 0, padding: 0 }}>
            {crons.map((c, i) => {
              const isCron = c.kind === "cron";
              const tagColor = isCron ? API_BLUE : API_FUCHSIA;
              return (
                <li key={i} style={{
                  display: "grid",
                  gridTemplateColumns: "72px minmax(0, 1fr)",
                  gap: 14, alignItems: "start",
                  padding: "12px 0",
                  borderBottom: i < crons.length - 1 ? `1px solid ${API_RULE_S}` : "none",
                }}>
                  <div style={{
                    fontFamily: API_MONO, fontSize: 10,
                    color: tagColor,
                    letterSpacing: "0.1em", textTransform: "uppercase",
                    padding: "4px 8px",
                    border: `1px solid ${tagColor}4d`,
                    borderRadius: 4,
                    textAlign: "center", fontWeight: 600,
                    background: `${tagColor}14`,
                    boxShadow: `0 0 10px ${tagColor}1a`,
                  }}>{c.kind}</div>
                  <div>
                    <div style={{ fontSize: 13.5, color: API_INK, fontWeight: 500, letterSpacing: "-0.005em" }}>{c.name}</div>
                    <div style={{ fontSize: 12, color: API_DIM, marginTop: 4, lineHeight: 1.55 }}>{c.sub}</div>
                  </div>
                </li>
              );
            })}
          </ul>
        </div>
      </div>
    </div>
    </ScaleFrame>
  );
}

window.CrmApiIngestionVisual = CrmApiIngestionVisual;
