/* ================================================================
   navbar.jsx — Capital Economics in-platform trial top navigation.
   Sticky navy chrome. The trial user's remaining credit balance is
   the most prominent element after the logo; a quiet upgrade path
   sits to the right. Adapts to mobile (nav collapses, balance stays).
   A small harness lets you switch credit states and device view.
================================================================ */
const { Button, Avatar } = window.CapitalEconomicsDesignSystem_f2a5b2;

const NS = "var(--font-ui)";
const SERIF = "var(--font-serif)";
const NAVY = "#1d233f"; /* matches the existing product chrome */

const ICONS = {
  search: <><circle cx="11" cy="11" r="8" /><path d="m21 21-4.3-4.3" /></>,
  menu: <><path d="M4 6h16M4 12h16M4 18h16" /></>,
  x: <><path d="M18 6 6 18M6 6l12 12" /></>,
  "chevron-down": <path d="m6 9 6 6 6-6" />,
  "file-text": <><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" /><path d="M14 2v6h6" /><path d="M16 13H8M16 17H8M10 9H8" /></>,
  "arrow-right": <><path d="M5 12h14" /><path d="m12 5 7 7-7 7" /></>,
  bell: <><path d="M10.268 21a2 2 0 0 0 3.464 0" /><path d="M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326" /></>,
};
function Icon({ name, size = 20, stroke = 2, style }) {
  return (
    <svg style={style} width={size} height={size} viewBox="0 0 24 24" fill="none"
      stroke="currentColor" strokeWidth={stroke} strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      {ICONS[name]}
    </svg>
  );
}

const NAV_ITEMS = ["Insights", "Data and Forecasts", "Economists"];

/* ---------------------------------------------------------------
   Credit balance — the priority element. Three markers + a legible
   count. Low (1 left) shifts to a warm amber so depletion is
   noticeable without alarming. Compact variant for mobile.
--------------------------------------------------------------- */
function CreditPill({ remaining, total = 3, compact = false }) {
  const low = remaining <= 1;
  const fillColour = low ? "#ecb84e" : "var(--ce-blue-light)";
  const textColour = low ? "#f3cd7a" : "rgba(255,255,255,0.92)";
  return (
    <div title={`${remaining} of ${total} free articles left`} style={{
      display: "flex", alignItems: "center", gap: compact ? 8 : 10,
      background: low ? "rgba(236,184,78,0.12)" : "rgba(255,255,255,0.08)",
      border: `1px solid ${low ? "rgba(236,184,78,0.4)" : "rgba(255,255,255,0.16)"}`,
      borderRadius: 999, padding: compact ? "6px 11px" : "7px 14px", whiteSpace: "nowrap",
    }}>
      <div style={{ display: "flex", gap: 4 }}>
        {Array.from({ length: total }).map((_, i) => (
          <span key={i} style={{
            width: 7, height: 7, borderRadius: "50%",
            background: i < remaining ? fillColour : "transparent",
            border: i < remaining ? "none" : "1px solid rgba(255,255,255,0.28)",
          }} />
        ))}
      </div>
      <span style={{
        fontFamily: NS, fontSize: compact ? 12.5 : 13.5, fontWeight: 700, color: textColour,
        fontVariantNumeric: "tabular-nums", letterSpacing: "0.005em",
      }}>
        {compact ? `${remaining} of ${total}` : `${remaining} of ${total} articles left`}
      </span>
    </div>
  );
}

function TrialTag() {
  return (
    <span style={{
      fontFamily: NS, fontSize: 10.5, fontWeight: 700, letterSpacing: "0.14em", textTransform: "uppercase",
      color: "var(--ce-blue-light)", border: "1px solid rgba(165,181,222,0.4)", borderRadius: 4,
      padding: "4px 8px", whiteSpace: "nowrap",
    }}>Free trial</span>
  );
}

function NavLink({ children }) {
  const [hover, setHover] = React.useState(false);
  return (
    <a href="#" onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)} style={{
      fontFamily: NS, fontSize: 14.5, fontWeight: 600, textDecoration: "none", whiteSpace: "nowrap",
      color: hover ? "#fff" : "rgba(255,255,255,0.8)", padding: "8px 2px",
    }}>{children}</a>
  );
}

function SearchField() {
  return (
    <div className="nav-search" style={{
      display: "flex", alignItems: "center", gap: 8, background: "rgba(255,255,255,0.08)",
      border: "1px solid rgba(255,255,255,0.14)", borderRadius: 8, padding: "0 12px", height: 36, width: 160,
      color: "rgba(255,255,255,0.55)",
    }}>
      <Icon name="search" size={16} />
      <input placeholder="Search" style={{
        border: 0, outline: 0, background: "transparent", color: "#fff", fontFamily: NS, fontSize: 14, width: "100%",
      }} />
    </div>
  );
}

/* Search icon button — shown in place of the field on narrower desktops. */
function SearchIconBtn() {
  return (
    <button className="nav-search-icon" aria-label="Search" style={{
      border: "1px solid rgba(255,255,255,0.14)", background: "rgba(255,255,255,0.08)", borderRadius: 8,
      width: 36, height: 36, cursor: "pointer", color: "rgba(255,255,255,0.8)", display: "none",
      alignItems: "center", justifyContent: "center",
    }}>
      <Icon name="search" size={17} />
    </button>
  );
}

/* ---------------------------------------------------------------
   The navbar.
--------------------------------------------------------------- */
function NavBar({ remaining, mobile }) {
  const [menuOpen, setMenuOpen] = React.useState(false);
  React.useEffect(() => { if (!mobile) setMenuOpen(false); }, [mobile]);

  return (
    <header style={{ position: "sticky", top: 0, zIndex: 30 }}>
      <div style={{
        background: NAVY, borderBottom: "1px solid rgba(255,255,255,0.12)",
        display: "flex", alignItems: "center", gap: mobile ? 12 : 22,
        padding: mobile ? "0 16px" : "0 28px", height: 64,
      }}>
        {/* Logo */}
        <a href="Homepage.html" style={{ display: "flex", flex: "0 0 auto" }} aria-label="Capital Economics">
          <img src="assets/CE-logo-reversed.png" alt="Capital Economics" style={{ height: mobile ? 30 : 40, display: "block" }} />
        </a>

        {/* Desktop primary nav */}
        {!mobile && (
          <nav className="nav-primary" style={{ display: "flex", alignItems: "center", gap: 22, marginLeft: 8 }}>
            {NAV_ITEMS.map((n) => <NavLink key={n}>{n}</NavLink>)}
          </nav>
        )}

        {/* Spacer */}
        <div style={{ flex: 1 }} />

        {!mobile && <><SearchField /><SearchIconBtn /></>}

        {/* Trial group (right) */}
        {!mobile ? (
          <div style={{ display: "flex", alignItems: "center", gap: 16 }}>
            <CreditPill remaining={remaining} />
            <TrialTag />
            <a href="#" className="nav-talk" style={{
              fontFamily: NS, fontSize: 14, fontWeight: 600, color: "rgba(255,255,255,0.8)", textDecoration: "none", whiteSpace: "nowrap",
            }}>Talk to our team</a>
            <Button variant="inverse" size="sm">Upgrade</Button>
            <button aria-label="Account" style={{ border: 0, background: "transparent", padding: 0, cursor: "pointer", display: "flex", alignItems: "center", gap: 4 }}>
              <Avatar name="Jordan Cole" size="sm" />
              <span style={{ color: "rgba(255,255,255,0.7)", display: "flex" }}><Icon name="chevron-down" size={16} /></span>
            </button>
          </div>
        ) : (
          /* Mobile right group — credit balance ALWAYS stays visible */
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <CreditPill remaining={remaining} compact />
            <button aria-label="Account" style={{ border: 0, background: "transparent", padding: 0, cursor: "pointer", display: "flex" }}>
              <Avatar name="Jordan Cole" size="sm" />
            </button>
            <button aria-label="Menu" onClick={() => setMenuOpen((o) => !o)} style={{
              border: 0, background: "transparent", padding: 4, cursor: "pointer", color: "#fff", display: "flex",
            }}>
              <Icon name={menuOpen ? "x" : "menu"} size={24} />
            </button>
          </div>
        )}
      </div>

      {/* Mobile collapsed menu */}
      {mobile && menuOpen && (
        <div style={{ background: NAVY, borderBottom: "1px solid rgba(255,255,255,0.12)", padding: "8px 16px 18px" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8, background: "rgba(255,255,255,0.08)", border: "1px solid rgba(255,255,255,0.14)", borderRadius: 8, padding: "0 12px", height: 40, color: "rgba(255,255,255,0.55)", marginBottom: 6 }}>
            <Icon name="search" size={16} />
            <input placeholder="Search" style={{ border: 0, outline: 0, background: "transparent", color: "#fff", fontFamily: NS, fontSize: 15, width: "100%" }} />
          </div>
          <nav style={{ display: "flex", flexDirection: "column" }}>
            {NAV_ITEMS.map((n) => (
              <a key={n} href="#" style={{ fontFamily: NS, fontSize: 16, fontWeight: 600, color: "rgba(255,255,255,0.88)", textDecoration: "none", padding: "12px 2px", borderBottom: "1px solid rgba(255,255,255,0.08)" }}>{n}</a>
            ))}
          </nav>
          <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 14, marginTop: 16 }}>
            <Button variant="inverse" size="md" block>Upgrade</Button>
            <a href="#" style={{ fontFamily: NS, fontSize: 14.5, fontWeight: 600, color: "rgba(255,255,255,0.82)", textDecoration: "none" }}>Talk to our team</a>
          </div>
        </div>
      )}
    </header>
  );
}

/* ---------------------------------------------------------------
   Placeholder research-hub content (proves sticky + context).
--------------------------------------------------------------- */
function PageBody({ mobile }) {
  const rows = [
    { kicker: "US Economics", time: "8 min read", title: "The Fed's December cut still looks likely despite sticky services inflation.", who: "Paul Ashworth" },
    { kicker: "UK Economics", time: "2h ago", title: "BoE holds at 4.0%, but the tone turned dovish. We've pulled our next cut forward to August.", who: "Paul Dales" },
    { kicker: "Commodities", time: "Yesterday", title: "Brent at $82 is mostly risk premium. Our oil model puts fair value near $68.", who: "David Oxley" },
    { kicker: "China", time: "2 days ago", title: "Q1 GDP of 5.2% flatters reality. The detail paints a weaker picture.", who: "Julian Evans-Pritchard" },
    { kicker: "Global Markets", time: "3 days ago", title: "The cost of capital has reset higher for the rest of the decade.", who: "Neil Shearing" },
  ];
  return (
    <div style={{ maxWidth: 1180, margin: "0 auto", padding: mobile ? "28px 18px 60px" : "44px 28px 90px" }}>
      <div className="ce-eyebrow" style={{ marginBottom: 14 }}>The insight desk · Updated hourly</div>
      <h1 style={{ fontFamily: SERIF, fontWeight: 600, fontSize: mobile ? 28 : 38, lineHeight: 1.1, letterSpacing: "-0.02em", color: "var(--text-primary)", margin: 0 }}>
        Insights
      </h1>
      <div style={{ height: 2, background: "var(--text-primary)", margin: "22px 0 0" }} />
      <div style={{ display: "flex", flexDirection: "column" }}>
        {rows.map((r, i) => (
          <a key={r.title} href="#" style={{
            display: "flex", flexDirection: "column", gap: 8, textDecoration: "none",
            padding: "22px 0", borderBottom: "1px solid var(--border-subtle)",
          }}>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12 }}>
              <span style={{ fontFamily: NS, fontWeight: 700, fontSize: 11, letterSpacing: "0.11em", textTransform: "uppercase", color: "var(--brand)" }}>{r.kicker}</span>
              <span style={{ fontFamily: NS, fontWeight: 700, fontSize: 12, letterSpacing: "0.06em", textTransform: "uppercase", color: "var(--text-muted)" }}>{r.time}</span>
            </div>
            <h3 style={{ fontFamily: SERIF, fontWeight: 600, fontSize: mobile ? 18 : 22, lineHeight: 1.22, letterSpacing: "-0.01em", color: "var(--text-primary)", margin: 0 }}>{r.title}</h3>
            <span style={{ fontFamily: NS, fontSize: 13.5, color: "var(--text-secondary)" }}>{r.who}</span>
          </a>
        ))}
      </div>
    </div>
  );
}

/* ---------------------------------------------------------------
   Demo harness — credit state + device toggles.
--------------------------------------------------------------- */
function Controls({ remaining, setRemaining, mobile, setMobile }) {
  const Seg = ({ active, onClick, children }) => (
    <button onClick={onClick} style={{
      border: 0, cursor: "pointer", fontFamily: NS, fontSize: 13, fontWeight: 700,
      padding: "7px 13px", borderRadius: 7,
      background: active ? "var(--brand)" : "transparent", color: active ? "#fff" : "var(--text-secondary)",
    }}>{children}</button>
  );
  return (
    <div style={{
      position: "fixed", bottom: 20, left: "50%", transform: "translateX(-50%)", zIndex: 100,
      display: "flex", alignItems: "center", gap: 14, background: "var(--surface-card)",
      border: "1px solid var(--border-default)", borderRadius: 12, boxShadow: "0 10px 34px rgba(36,33,58,0.18)",
      padding: "9px 12px",
    }}>
      <span style={{ fontFamily: NS, fontSize: 11, fontWeight: 700, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--text-muted)", paddingLeft: 4 }}>Credits</span>
      <div style={{ display: "flex", gap: 2, background: "var(--surface-sunken)", borderRadius: 9, padding: 3 }}>
        {[3, 2, 1].map((n) => <Seg key={n} active={remaining === n} onClick={() => setRemaining(n)}>{n} of 3</Seg>)}
      </div>
      <div style={{ width: 1, height: 24, background: "var(--border-default)" }} />
      <span style={{ fontFamily: NS, fontSize: 11, fontWeight: 700, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--text-muted)" }}>View</span>
      <div style={{ display: "flex", gap: 2, background: "var(--surface-sunken)", borderRadius: 9, padding: 3 }}>
        <Seg active={!mobile} onClick={() => setMobile(false)}>Desktop</Seg>
        <Seg active={mobile} onClick={() => setMobile(true)}>Mobile</Seg>
      </div>
    </div>
  );
}

function App() {
  const [remaining, setRemaining] = React.useState(2);
  const [mobile, setMobile] = React.useState(false);

  return (
    <div style={{ minHeight: "100vh", background: mobile ? "var(--surface-sunken)" : "var(--surface-page)" }}>
      {mobile ? (
        <div style={{ display: "flex", justifyContent: "center", padding: "40px 16px 110px" }}>
          {/* Simple phone frame with its own scroll, so sticky is visible */}
          <div style={{
            width: 390, height: 760, background: "var(--surface-page)", borderRadius: 38,
            border: "10px solid #11152b", boxShadow: "0 24px 60px rgba(17,21,43,0.32)", overflow: "hidden",
            display: "flex", flexDirection: "column",
          }}>
            <div style={{ flex: 1, overflowY: "auto" }}>
              <NavBar remaining={remaining} mobile />
              <PageBody mobile />
            </div>
          </div>
        </div>
      ) : (
        <>
          <NavBar remaining={remaining} mobile={false} />
          <PageBody mobile={false} />
        </>
      )}
      <Controls remaining={remaining} setRemaining={setRemaining} mobile={mobile} setMobile={setMobile} />
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
