// Monitor data — landing page (simplified)
const { useState, useEffect, useMemo } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#ff7a45",
  "density": "comfy",
  "fonts": "serif",
  "heroVariant": "editorial"
}/*EDITMODE-END*/;

const ACCENT_OPTIONS = ["#ff7a45", "#7c5cff", "#3ecf8e", "#4d9fff", "#ededed"];

const SITE_ORIGIN = window.location.origin && window.location.origin !== "null"
  ? window.location.origin
  : "https://monitors.api";

const PROMPT_TEXT =
`Use ${SITE_ORIGIN}/llms.txt
then call /v1/status and query the monitor API.`;

const COPYABLE_PROMPT =
`Use ${SITE_ORIGIN}/llms.txt, call /v1/status, then query the monitor API for my monitor question.`;

// ---------- typing hook ----------
function useTypewriter(text, speed = 22, startDelay = 500) {
  const [out, setOut] = useState("");
  const [done, setDone] = useState(false);
  useEffect(() => {
    let i = 0; let cancelled = false;
    setOut(""); setDone(false);
    const start = setTimeout(() => {
      const tick = () => {
        if (cancelled) return;
        i++;
        setOut(text.slice(0, i));
        if (i < text.length) {
          const ch = text[i] || "";
          const delay = ch === "\n" ? speed * 6 : (ch === " " ? speed * 0.6 : speed + (Math.random() * 14 - 7));
          setTimeout(tick, delay);
        } else { setDone(true); }
      };
      tick();
    }, startDelay);
    return () => { cancelled = true; clearTimeout(start); };
  }, [text, speed, startDelay]);
  return { out, done };
}

function CopyBtn({ text, label = "Copy" }) {
  const [ok, setOk] = useState(false);
  const onClick = async () => {
    try {
      await navigator.clipboard.writeText(text);
      setOk(true);
      setTimeout(() => setOk(false), 1400);
    } catch (e) {}
  };
  return (
    <button className={"copy-btn" + (ok ? " ok" : "")} onClick={onClick}>
      <span>{ok ? "Copied" : label}</span>
      <span style={{ fontSize: 10 }}>{ok ? "✓" : "⧉"}</span>
    </button>
  );
}

// ---------- Nav ----------
function Nav() {
  return (
    <nav className="nav">
      <div className="container nav-inner">
        <a href="#" className="brand">
          <span className="brand-mark"></span>
          <span className="brand-name">monitors<b>.api</b></span>
        </a>
        <div className="nav-links">
          <a href="#how">How it works</a>
          <a href="#faq">FAQ</a>
        </div>
        <div className="nav-cta">
        </div>
      </div>
    </nav>
  );
}

// ---------- Hero ----------
function Hero({ variant }) {
  const { out, done } = useTypewriter(PROMPT_TEXT, 24, 600);

  const colored = useMemo(() => {
    return out.split("\n").map((ln, i) => {
      const parts = ln.split(/(https?:\/\/\S+)/g).map((p, j) =>
        /^https?:/.test(p) ? <span key={j} className="k">{p}</span> : <span key={j}>{p}</span>
      );
      return <span key={i}>{parts}{"\n"}</span>;
    });
  }, [out]);

  return (
    <section className="hero">
      <div className="container">
        {variant === "editorial" && (
          <h1>
            Monitor data,<br />
            <span className="it">queryable.</span>
          </h1>
        )}
        {variant === "stacked" && (
          <h1>
            Every monitor.<br />
            <span className="it">One endpoint.</span>
          </h1>
        )}
        {variant === "stroke" && (
          <h1>
            <span className="stroke">Bring an</span> <span className="it">assistant.</span>
          </h1>
        )}

        <p className="hero-sub">
          Structured for assistants, not browsers.
        </p>

        <div className="prompt-card" style={{ marginTop: 56, maxWidth: 680, marginLeft: "auto", marginRight: "auto" }}>
          <div className="prompt-head">
            <div className="label">paste into your assistant</div>
            <CopyBtn text={COPYABLE_PROMPT} label="Copy" />
          </div>
          <div className="prompt-body">
            {colored}
            {!done && <span className="caret"></span>}
          </div>
        </div>
      </div>
    </section>
  );
}

// ---------- How it works ----------
function HowItWorks() {
  return (
    <section className="block" id="how" style={{ borderTop: "1px solid var(--line)" }}>
      <div className="container">
        <div style={{ maxWidth: 760, margin: "0 auto" }}>
          <h2 className="section-h2">
            Not for browsing.<br />
            <span className="it">For asking.</span>
          </h2>
          <p className="lede">
            There's no search bar here. Open any assistant that can fetch URLs, point it at this site, and let it read the API contract.
          </p>
        </div>

        <div className="steps">
          <Step n="01" t="Paste the prompt above into your assistant." />
          <Step n="02" t="Your assistant reads the contract and schema." />
          <Step n="03" t="It checks /v1/status, queries the live API, and answers in its own voice." />
        </div>
      </div>
    </section>
  );
}
function Step({ n, t }) {
  return (
    <div className="step">
      <div className="step-n">{n}</div>
      <div className="step-t">{t}</div>
    </div>
  );
}

// ---------- Endpoints (removed) ----------
function _RemovedEndpoints() {
  return (
    <section style={{display:"none"}}>
      <div>
        <div></div>
        <div className="endpoint-list">
          {ENDPOINTS.map((e, i) => (
            <div className="endpoint-row" key={i}>
              <div className="path">{e.p}{e.t && <span className="dim">{e.t}</span>}</div>
              <div className="desc">{e.d}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ---------- FAQ ----------
const FAQS = [
  {
    q: "Is it free?",
    a: "Yes. The public API is planned to be free to use with reasonable rate limits."
  },
  {
    q: "Is the catalog API live?",
    a: "Yes. The deterministic API is backed by Supabase Postgres. Assistants should call /v1/status first and treat backend_live as the source of truth."
  },
  {
    q: "Why no search bar?",
    a: "This is a data source, not a consumer site. The intended interface is an assistant reading the API contract."
  },
  {
    q: "Which assistants work?",
    a: "Any assistant or tool that can fetch URLs or read llms.txt."
  },
  {
    q: "What does the API contain?",
    a: "Structured monitor specs, measurements, rankings, filters, comparison fields, community sentiment, and Reddit opinion tags where available."
  },
  {
    q: "Can I read the API myself?",
    a: "The machine-readable docs and API are meant for URL-capable assistants. Humans should paste the prompt above into ChatGPT, Claude, Perplexity, or a similar assistant."
  },
  {
    q: "Does it quote sources?",
    a: "No. Public responses use normalized facts, controlled labels, counts, and scores. They should not expose raw reviews, Reddit comments, source names, or copied prose."
  }
];

function FAQ() {
  const [open, setOpen] = useState(0);
  return (
    <section className="block" id="faq" style={{ borderTop: "1px solid var(--line)" }}>
      <div className="container">
        <div style={{ maxWidth: 760, marginBottom: 32, marginLeft: "auto", marginRight: "auto" }}>
          <h2 className="section-h2">Questions.</h2>
        </div>

        <div className="faq-list">
          {FAQS.map((f, i) => (
            <div className={"faq-item" + (open === i ? " open" : "")}
                 key={i}
                 onClick={() => setOpen(open === i ? -1 : i)}>
              <div>
                <div className="faq-q">
                  <span>{f.q}</span>
                  <span className="faq-toggle">+</span>
                </div>
                <div className="faq-a">{f.a}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ---------- Footer ----------
function Footer() {
  return (
    <footer className="foot">
      <div className="container">
        <div className="foot-bottom">
          <span>© 2026</span>
          <span className="brand">
            <span className="brand-mark"></span>
            <span className="brand-name">monitors<b>.api</b></span>
          </span>
        </div>
      </div>
    </footer>
  );
}

// ---------- Tweaks ----------
function Tweaks() {
  const [t, setTweak] = window.useTweaks(TWEAK_DEFAULTS);
  useEffect(() => {
    document.body.dataset.density = t.density;
    document.body.dataset.fonts = t.fonts;
    document.documentElement.style.setProperty("--accent", t.accent);
    const hex = t.accent.replace("#", "");
    const r = parseInt(hex.slice(0,2),16), g = parseInt(hex.slice(2,4),16), b = parseInt(hex.slice(4,6),16);
    document.documentElement.style.setProperty("--accent-soft", `rgba(${r},${g},${b},0.12)`);
    document.documentElement.style.setProperty("--accent-line", `rgba(${r},${g},${b},0.35)`);
  }, [t]);

  const TP = window.TweaksPanel;
  const TS = window.TweakSection;
  const TC = window.TweakColor;
  const TR = window.TweakRadio;
  const TSel = window.TweakSelect;
  if (!TP) return null;

  return (
    <TP title="Tweaks">
      <TS title="Accent">
        <TC label="Accent" options={ACCENT_OPTIONS} value={t.accent} onChange={(v) => setTweak("accent", v)} />
      </TS>
      <TS title="Layout">
        <TR label="Density" options={[{label:"Compact", value:"compact"},{label:"Comfy", value:"comfy"}]}
            value={t.density} onChange={(v) => setTweak("density", v)} />
        <TR label="Hero"
            options={[{label:"Editorial", value:"editorial"},{label:"Stacked", value:"stacked"},{label:"Stroke", value:"stroke"}]}
            value={t.heroVariant} onChange={(v) => setTweak("heroVariant", v)} />
      </TS>
      <TS title="Type">
        <TSel label="Display"
            options={[
              {label:"Instrument Serif", value:"serif"},
              {label:"Fraunces", value:"fraunces"},
              {label:"Mono", value:"mono-display"}
            ]}
            value={t.fonts} onChange={(v) => setTweak("fonts", v)} />
      </TS>
    </TP>
  );
}

// ---------- App ----------
function App() {
  const [t] = window.useTweaks(TWEAK_DEFAULTS);
  return (
    <>
      <Nav />
      <Hero variant={t.heroVariant} />
      <HowItWorks />
      <FAQ />
      <Footer />
      <Tweaks />
    </>
  );
}

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