/* global React */
const { useState, useEffect, useRef } = React;

/* ============================================================
   Shared building blocks: Brand, Header, Footer, formatters,
   icons, and small UI atoms.
   ============================================================ */

/* ---------- formatters ---------- */
const fmtUSD = (n, opts = {}) =>
  new Intl.NumberFormat("en-US", {
    style: "currency", currency: "USD",
    maximumFractionDigits: 0, ...opts,
  }).format(n);
const fmtUSDc = (n) => fmtUSD(n, { maximumFractionDigits: 2, minimumFractionDigits: 2 });
const fmtPct = (n, d = 2) => `${n.toFixed(d)}%`;
const fmtMonth = (date) => date.toLocaleDateString("en-US", { month: "short", year: "numeric" });

window.fmtUSD = fmtUSD; window.fmtUSDc = fmtUSDc; window.fmtPct = fmtPct; window.fmtMonth = fmtMonth;

/* ---------- icons ---------- */
const Icon = ({ name, size = 16, ...rest }) => {
  const paths = {
    search: <><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></>,
    arrow: <path d="M5 12h14M13 5l7 7-7 7"/>,
    sparkle: <path d="M12 3l1.6 4.4L18 9l-4.4 1.6L12 15l-1.6-4.4L6 9l4.4-1.6L12 3z"/>,
    chevdown: <path d="m6 9 6 6 6-6"/>,
    chevright: <path d="m9 6 6 6-6 6"/>,
    bookmark: <path d="M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z"/>,
    share: <><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><path d="m8.6 13.5 6.8 4M15.4 6.5l-6.8 4"/></>,
    code: <><path d="m16 18 6-6-6-6"/><path d="m8 6-6 6 6 6"/></>,
    info: <><circle cx="12" cy="12" r="10"/><path d="M12 16v-4M12 8h.01"/></>,
    plus: <path d="M12 5v14M5 12h14"/>,
    x: <path d="m18 6-12 12M6 6l12 12"/>,
    print: <><path d="M6 9V2h12v7M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2"/><rect x="6" y="14" width="12" height="8"/></>,
    sun: <><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"/></>,
  };
  return (
    <svg
      xmlns="http://www.w3.org/2000/svg" width={size} height={size}
      viewBox="0 0 24 24" fill="none" stroke="currentColor"
      strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round"
      {...rest}
    >{paths[name]}</svg>
  );
};
window.Icon = Icon;

/* ---------- Brand wordmark (Direction D) ---------- */
const Brand = ({ size = "default", domain = false }) => {
  const cls = "dc-brand" + (size === "lg" ? " lg" : size === "xl" ? " xl" : "");
  return (
    <span className={cls}>
      <span>digicalc</span>
      <span className="dot" aria-hidden="true"></span>
      {domain && (
        <span style={{ color: "var(--muted)", fontWeight: 500, marginLeft: ".18em", letterSpacing: 0 }}>
          online
        </span>
      )}
    </span>
  );
};
window.Brand = Brand;

/* ---------- Header ---------- */
const Header = () => {
  const [openSearch, setOpenSearch] = useState(false);
  return (
    <>
      <header className="dc-header">
        <div className="dc-shell">
          <div className="dc-header-row">
            <a href="/" aria-label="DigiCalc home">
              <Brand />
            </a>
            <span className="grow" />
            <button
              className="dc-search-trigger"
              onClick={() => setOpenSearch(true)}
              aria-label="Find a calculator"
            >
              <Icon name="search" />
              <span>Find a calculator…</span>
              <span className="kbd">⌘K</span>
            </button>
            <span className="grow" />
            <nav className="nav-links">
              <a href="#methodology" onClick={(e) => e.preventDefault()}>Methodology</a>
              <a href="#embed" onClick={(e) => e.preventDefault()}>Embed</a>
              <a href="#blog" onClick={(e) => e.preventDefault()}>Blog</a>
              <a className="signin" href="#signin" onClick={(e) => e.preventDefault()}>Sign in</a>
            </nav>
          </div>
        </div>
      </header>
      {openSearch && <CommandPalette onClose={() => setOpenSearch(false)} />}
    </>
  );
};
window.Header = Header;

/* ---------- Footer ---------- */
const Footer = () => (
  <footer className="dc-footer">
    <div className="dc-shell">
      <div className="dc-footer-grid">
        <div>
          <Brand domain />
          <p style={{ color: "var(--muted)", maxWidth: 320, marginTop: 12, fontSize: 14 }}>
            Online calculators that respect your time. Free, beautifully built, plainly explained.
          </p>
        </div>
        <div>
          <h5>Calculators</h5>
          <ul>
            <li><a href="#">Finance</a></li>
            <li><a href="#">Health</a></li>
            <li><a href="#">Time &amp; Date</a></li>
            <li><a href="#">Tax &amp; Business</a></li>
          </ul>
        </div>
        <div>
          <h5>Build with us</h5>
          <ul>
            <li><a href="#">Embed widgets</a></li>
            <li><a href="#">API (beta)</a></li>
            <li><a href="#">Methodology</a></li>
            <li><a href="#">Changelog</a></li>
          </ul>
        </div>
        <div>
          <h5>Company</h5>
          <ul>
            <li><a href="#">About</a></li>
            <li><a href="#">Contact</a></li>
            <li><a href="#">Privacy</a></li>
            <li><a href="#">Terms</a></li>
          </ul>
        </div>
      </div>
      <div className="legal">
        <span>© 2026 DigiCalc, Inc.</span>
        <span>Calculations are estimates — verify with a professional before big decisions.</span>
      </div>
    </div>
  </footer>
);
window.Footer = Footer;

/* ---------- Command Palette (search overlay) ---------- */
const ALL_CALCS = [
  { id: "mortgage", name: "Mortgage Calculator", cat: "Finance", popular: true },
  { id: "auto", name: "Auto Loan Calculator", cat: "Finance" },
  { id: "compound", name: "Compound Interest", cat: "Finance" },
  { id: "retirement", name: "Retirement Calculator", cat: "Finance" },
  { id: "refi", name: "Refinance Calculator", cat: "Finance" },
  { id: "loan-comp", name: "Loan Comparison", cat: "Finance" },
  { id: "bmi", name: "BMI Calculator", cat: "Health" },
  { id: "calorie", name: "Calorie Calculator", cat: "Health", popular: true },
  { id: "macro", name: "Macro Calculator", cat: "Health" },
  { id: "bodyfat", name: "Body Fat", cat: "Health" },
  { id: "pregnancy", name: "Pregnancy Due Date", cat: "Health" },
  { id: "age", name: "Age Calculator", cat: "Time & Date", popular: true },
  { id: "countdown", name: "Countdown", cat: "Time & Date" },
  { id: "timezone", name: "Time Zone Converter", cat: "Time & Date" },
  { id: "datediff", name: "Date Difference", cat: "Time & Date" },
  { id: "salestax", name: "Sales Tax Calculator", cat: "Tax & Business", popular: true },
  { id: "income-tax", name: "Income Tax Estimator", cat: "Tax & Business" },
  { id: "payroll", name: "Payroll Calculator", cat: "Tax & Business" },
  { id: "roi", name: "ROI Calculator", cat: "Tax & Business" },
];
window.ALL_CALCS = ALL_CALCS;

const CALC_URLS = {
  mortgage: "/calcs/mortgage/",
};

const CommandPalette = ({ onClose }) => {
  const [q, setQ] = useState("");
  const inputRef = useRef(null);
  useEffect(() => { inputRef.current?.focus(); }, []);
  useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [onClose]);

  const results = ALL_CALCS.filter((c) =>
    !q ? true : (c.name + " " + c.cat).toLowerCase().includes(q.toLowerCase())
  ).slice(0, 8);

  return (
    <div
      onClick={onClose}
      style={{
        position: "fixed", inset: 0, zIndex: 100,
        background: "rgba(10,11,13,.4)", backdropFilter: "blur(6px)",
        display: "flex", alignItems: "flex-start", justifyContent: "center", paddingTop: "12vh",
      }}
    >
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          width: "min(560px, 90vw)", background: "var(--surface)",
          border: "1px solid var(--rule)", borderRadius: 14, overflow: "hidden",
          boxShadow: "var(--shadow-pop)",
        }}
      >
        <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "16px 18px", borderBottom: "1px solid var(--rule)" }}>
          <Icon name="search" size={18} style={{ color: "var(--muted)" }} />
          <input
            ref={inputRef}
            value={q} onChange={(e) => setQ(e.target.value)}
            placeholder="Find a calculator…"
            style={{
              flex: 1, border: 0, outline: 0, background: "transparent",
              fontFamily: "var(--font-ui)", fontSize: 17, color: "var(--ink)",
            }}
          />
          <span className="dc-kbd">esc</span>
        </div>
        <div style={{ maxHeight: 420, overflowY: "auto", padding: 8 }}>
          {results.length === 0 && (
            <div style={{ padding: 24, textAlign: "center", color: "var(--muted)" }}>No matches.</div>
          )}
          {results.map((c) => (
            <button
              key={c.id}
              onClick={() => { onClose(); if (CALC_URLS[c.id]) window.location.href = CALC_URLS[c.id]; }}
              style={{
                width: "100%", display: "flex", alignItems: "center", gap: 12,
                padding: "10px 12px", border: 0, background: "transparent",
                borderRadius: 8, cursor: "pointer", color: "var(--ink)", textAlign: "left",
                fontSize: 14, fontFamily: "var(--font-ui)",
              }}
              onMouseEnter={(e) => e.currentTarget.style.background = "var(--surface-2)"}
              onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}
            >
              <span style={{ flex: 1 }}>{c.name}</span>
              <span style={{ fontSize: 12, color: "var(--muted)" }}>{c.cat}</span>
              <Icon name="chevright" size={14} style={{ color: "var(--faint)" }} />
            </button>
          ))}
        </div>
        <div style={{
          display: "flex", justifyContent: "space-between",
          padding: "10px 16px", borderTop: "1px solid var(--rule)",
          fontSize: 12, color: "var(--muted)", background: "var(--surface-2)",
        }}>
          <span><span className="dc-kbd">↑</span> <span className="dc-kbd">↓</span> navigate</span>
          <span><span className="dc-kbd">↵</span> open</span>
          <span>{ALL_CALCS.length} calculators</span>
        </div>
      </div>
    </div>
  );
};
window.CommandPalette = CommandPalette;
