/* global React, ReactDOM, IOSDevice, useTweaks, TweaksPanel, TweakSection, TweakRadio */
const { useState, useEffect } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "dark",
  "journey": "Compare",
  "naming": "Connected / Private",
  "context": "Onboarding",
  "billing": "annual"
}/*EDITMODE-END*/;

function Content({ t, variant }) {
  const { C2, I, Billing, PlanCard, Matrix, Hero } = window.C2KIT;
  const naming = t.naming === "Connected / Private";
  const context = t.context === "Change plan" ? "change" : "onboarding";
  const [billing, setBilling] = useState(t.billing);
  useEffect(()=>setBilling(t.billing), [t.billing]);

  // guided flow state
  const [step, setStep] = useState(0); // 0 cadence, 1 privacy, 2 result
  const [ans, setAns] = useState({ cadence: null, privacy: null });
  const [chosen, setChosen] = useState("private");

  // reset journey when tweaks change
  useEffect(()=>{ setStep(0); setAns({cadence:null,privacy:null}); }, [t.journey, t.context]);

  // recommendation: any "unlimited" or "max privacy" answer → Private
  const recommend = (ans.cadence==="unlimited" || ans.privacy==="max") ? "private"
    : (ans.cadence==="few" && ans.privacy==="standard") ? "connected" : "private";

  const CurrentBanner = () => context==="change" ? (
    <div className="c2-current">{I.check(16)} Your plan: Connected · Annual — renews 13 Jun 2026</div>
  ) : null;

  const TrialFootnotes = () => (
    <ul className="c2-fine">
      <li>{I.info(13)}<span><strong>Connected</strong> needs an active <strong>Claude Pro or Max</strong> plan and is bounded by Claude's included routine runs (~5/day Pro, ~15/day Max). <strong>Private</strong> uses your own Anthropic API key — no Claude subscription.</span></li>
      <li>{I.info(13)}<span>7 days free, then your plan starts automatically. We'll remind you 2 days before. Cancel anytime in the App Store.</span></li>
      <li>{I.info(13)}<span>By starting a trial you agree to our <a href="/terms" style={{color:"var(--accent)",fontWeight:700}}>Terms</a> &amp; <a href="/privacy" style={{color:"var(--accent)",fontWeight:700}}>Privacy Policy</a>.</span></li>
    </ul>
  );

  /* ── GUIDED JOURNEY ── */
  if (t.journey === "Guided") {
    const Q = ({ eyebrow, title, sub, options, value, onPick, idx }) => (
      <>
        <div className="c2-progress">
          {[0,1].map(i=><span key={i} className={i<idx?"done":i===idx?"on":""}/>)}
        </div>
        <div className="c2-q-eyebrow">{eyebrow}</div>
        <h2 className="c2-q-title">{title}</h2>
        <p className="c2-q-sub">{sub}</p>
        <div className="c2-opts">
          {options.map(o=>(
            <button key={o.k} className={`c2-opt ${o.alt?"alt":""} ${value===o.k?"on":""}`} onClick={()=>onPick(o.k)}>
              <span className="c2-opt-ic">{o.ic}</span>
              <span className="c2-opt-body"><span className="c2-opt-t">{o.t}</span><span className="c2-opt-d">{o.d}</span></span>
              <span className="c2-opt-radio"><i/></span>
            </button>
          ))}
        </div>
      </>
    );

    return (
      <div className={`c2-root ${variant}`}>
        <div className="c2-bg"/>
        <div className="c2-scroll"><div className="c2-page"><div className="c2-wrap">
          {step>0 && step<2 && <button className="c2-back" onClick={()=>setStep(step-1)}>{I.back(14)} Back</button>}
          {step===2 && <button className="c2-back" onClick={()=>setStep(1)}>{I.back(14)} Change answers</button>}

          {step===0 && <Hero context={context} />}
          <CurrentBanner/>

          {step===0 && (
            <Q idx={0} eyebrow="2 quick questions · question 1"
              title="How often should What's On check your mail?"
              sub="This is the real difference between the plans — how fresh your task board stays."
              value={ans.cadence}
              onPick={(k)=>{ setAns(a=>({...a,cadence:k})); setTimeout(()=>setStep(1),180); }}
              options={[
                { k:"few", alt:true, ic:I.clock(20), t:"A few times a day is fine", d:"Morning, midday, evening. Bounded by your Claude plan's included runs (~5/day Pro)." },
                { k:"unlimited", ic:I.infinity(20), t:"I want it whenever I need it", d:"Unlimited, on-demand triage — your board's never more than a tap behind." },
              ]}/>
          )}

          {step===1 && (
            <Q idx={1} eyebrow="2 quick questions · question 2"
              title="How private does triage need to be?"
              sub="Where the AI reads your mail. Both are private — one is absolute."
              value={ans.privacy}
              onPick={(k)=>{ setAns(a=>({...a,privacy:k})); setTimeout(()=>setStep(2),180); }}
              options={[
                { k:"standard", alt:true, ic:I.cloud(20), t:"Standard is fine", d:"Triage runs inside my own Claude account. No ads, no resale." },
                { k:"max", ic:I.lock(20), t:"Maximum — on my device only", d:"On-device & content-blind. Nothing leaves except calls to Anthropic." },
              ]}/>
          )}

          {step===2 && (()=>{
            const recP = C2[recommend], altP = C2[recommend==="private"?"connected":"private"];
            const price = recP.price[billing], period = billing==="annual"?"/year":"/month";
            return (
              <>
                <div className="c2-q-eyebrow">Your match</div>
                <h2 className="c2-q-title" style={{marginBottom:14}}>
                  {recommend==="private" ? "Go Private — unlimited & on-device" : "Connected is your sweet spot"}
                </h2>
                <Billing billing={billing} set={setBilling}/>
                <div className="c2-cards">
                  <PlanCard p={recP} billing={billing} naming={naming} selected={chosen===recP.id}
                    onSelect={setChosen} badge="Recommended for you"/>
                  <PlanCard p={altP} billing={billing} naming={naming} selected={chosen===altP.id}
                    onSelect={setChosen}/>
                </div>
                <div className="c2-note">{I.info(14)}<span>Heads up: we're still measuring real-world <strong>API token cost</strong> for incremental updates on Private. Treat its all-in estimate as a ballpark, not a promise.</span></div>
                <div className="c2-spacer"/>
                <button className="c2-cta">
                  <span className="c2-cta-main">Start 7-day free trial</span>
                  <span className="c2-cta-sub">then {C2[chosen].price[billing]}{period} · {planLead(chosen, naming)}</span>
                </button>
                <div className="c2-cta-foot">7 days free · cancel anytime before then</div>
                <TrialFootnotes/>
                <EarlyAccess/>
              </>
            );
          })()}
        </div></div></div>
      </div>
    );
  }

  /* ── COMPARE JOURNEY ── */
  const period = billing==="annual"?"/year":"/month";
  return (
    <div className={`c2-root ${variant}`}>
      <div className="c2-bg"/>
      <div className="c2-scroll"><div className="c2-page"><div className="c2-wrap">
        <Hero context={context} />
        <CurrentBanner/>

        <div className="c2-prereq">
          <span className="pic">{I.claude(20)}</span>
          <div><div className="pt">Both plans run on Claude — you choose how</div>
            <div className="pd"><b>Connected</b> rides a Claude Pro/Max plan you already pay for. <b>Private</b> needs only an Anthropic API key. The choice is about <b>cadence, privacy and cost shape</b> — not which is "better".</div></div>
        </div>

        <Matrix naming={naming}/>
        <Billing billing={billing} set={setBilling}/>

        <div className="c2-cards">
          <PlanCard p={C2.private} billing={billing} naming={naming} selected={chosen==="private"} onSelect={setChosen} badge="Most popular · unlimited"/>
          <PlanCard p={C2.connected} billing={billing} naming={naming} selected={chosen==="connected"} onSelect={setChosen}/>
        </div>

        <div className="c2-note">{I.info(14)}<span>We're still measuring real <strong>API token cost</strong> for incremental updates on Private — its all-in figure is an estimate. Connected's cost is flat and known.</span></div>

        <div className="c2-spacer"/>
        <button className="c2-cta">
          <span className="c2-cta-main">Start 7-day free trial</span>
          <span className="c2-cta-sub">then {C2[chosen].price[billing]}{period} · {planLead(chosen, naming)}</span>
        </button>
        <div className="c2-cta-foot">7 days free · cancel anytime before then</div>
        <TrialFootnotes/>
        <EarlyAccess/>
      </div></div></div>
    </div>
  );
}
function planLead(id, naming) {
  return naming ? (id==="connected"?"Connected":"Private") : (id==="connected"?"Standard":"Premium");
}

/* Repeated Get-early-access capture — mirrors the marketing site's hero form
   (neon-bordered email + button, posts to the same endpoint). */
function EarlyAccess() {
  const { I } = window.C2KIT;
  const [val, setVal] = useState("");
  const [done, setDone] = useState(false);
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState("");
  const submit = async (e) => {
    e.preventDefault();
    if (!/.+@.+\..+/.test(val)) { setErr("Please enter a valid email address."); return; }
    setBusy(true); setErr("");
    try {
      const r = await fetch("/forms/early-access", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email: val.trim(), source: "comingsoon" }),
      });
      if (!r.ok) throw new Error("status " + r.status);
      setDone(true);
    } catch (_) { setErr("Something went wrong — please try again in a moment."); }
    finally { setBusy(false); }
  };
  return (
    <div className="c2-ea">
      <div className="c2-ea-badge"><span className="c2-ea-pulse"/>BETA · COMING SOON TO APPLE</div>
      <h3 className="c2-ea-h">Be first through the door.</h3>
      <p className="c2-ea-p">Launching first on Apple — iPhone &amp; Mac. Drop your email and we'll tell you the moment the beta opens.</p>
      {done ? (
        <div className="c2-ea-done">{I.check(16)} You're on the list — we'll email you the moment the beta opens.</div>
      ) : (
        <form className="c2-ea-form" onSubmit={submit}>
          <input type="email" required placeholder="you@example.com" value={val}
            onChange={e=>{ setVal(e.target.value); if(err) setErr(""); }} aria-label="Email address" disabled={busy}/>
          <button type="submit" className="c2-ea-btn" disabled={busy}>{busy ? "Adding you…" : "Get early access"}</button>
          {err && <div className="c2-ea-err" role="alert">{err}</div>}
        </form>
      )}
    </div>
  );
}

function MacChrome({ width, height, dark, children }) {
  return (
    <div style={{ width, height, borderRadius:14, overflow:"hidden", background:dark?"#000":"#fff",
      boxShadow:"0 0 0 1px rgba(0,0,0,0.5), 0 30px 70px rgba(0,0,0,0.55)", position:"relative" }}>
      <div style={{ position:"absolute", top:0, left:0, right:0, height:30, zIndex:40,
        background:dark?"rgba(18,10,28,0.9)":"rgba(250,247,255,0.92)", backdropFilter:"blur(20px)",
        borderBottom:dark?"1px solid rgba(255,255,255,0.08)":"1px solid rgba(28,16,42,0.1)",
        display:"flex", alignItems:"center", padding:"0 12px", gap:8 }}>
        <span style={{width:12,height:12,borderRadius:"50%",background:"#ff5f57"}}/>
        <span style={{width:12,height:12,borderRadius:"50%",background:"#febc2e"}}/>
        <span style={{width:12,height:12,borderRadius:"50%",background:"#28c840"}}/>
        <div style={{flex:1,textAlign:"center",fontSize:12,fontWeight:600,color:dark?"rgba(255,255,255,0.7)":"rgba(40,28,60,0.7)"}}>What's On</div>
        <div style={{width:54}}/>
      </div>
      <div style={{position:"absolute",top:30,left:0,right:0,bottom:0}}>{children}</div>
    </div>
  );
}

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const prefersDark = window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches;
  const resolved = t.theme === "auto" ? (prefersDark?"dark":"light") : t.theme;
  const dark = resolved === "dark";

  // Pick ONE version for the visitor: phones (portrait) get the mobile layout,
  // laptops & tablets get the desktop layout. Re-evaluates on resize/rotate.
  const [mobile, setMobile] = useState(
    typeof window !== "undefined" ? window.matchMedia("(max-width: 759px)").matches : false
  );
  useEffect(()=>{
    const mq = window.matchMedia("(max-width: 759px)");
    const on = ()=> setMobile(mq.matches);
    on();
    if (mq.addEventListener) mq.addEventListener("change", on); else mq.addListener(on);
    return ()=>{ if (mq.removeEventListener) mq.removeEventListener("change", on); else mq.removeListener(on); };
  },[]);

  return (
    <>
      <div className={`theme-${resolved} c2-fullbleed`}>
        <Content t={t} variant={mobile ? "c2-ios" : "c2-mac"} />
      </div>

      <TweaksPanel title="Tweaks">
        <TweakSection label="Journey" />
        <TweakRadio label="Approach" value={t.journey} options={["Guided","Compare"]} onChange={(v)=>setTweak("journey",v)} />
        <TweakSection label="Plan naming" />
        <TweakRadio label="Names" value={t.naming} options={["Connected / Private","Standard / Premium"]} onChange={(v)=>setTweak("naming",v)} />
        <TweakSection label="Context" />
        <TweakRadio label="Shown as" value={t.context} options={["Onboarding","Change plan"]} onChange={(v)=>setTweak("context",v)} />
        <TweakSection label="Billing" />
        <TweakRadio label="Billing" value={t.billing} options={["monthly","annual"]} onChange={(v)=>setTweak("billing",v)} />
        <TweakSection label="Appearance" />
        <TweakRadio label="Theme" value={t.theme} options={["dark","light","auto"]} onChange={(v)=>setTweak("theme",v)} />
      </TweaksPanel>
    </>
  );
}
ReactDOM.createRoot(document.getElementById("root")).render(<App/>);
