// Klombic — Order flow wizard

const ARCHETYPES = [
  { id:"operator", name:"Operator", egs:"Linear · Stripe · Plausible", glyph:(<rect x="6" y="14" width="20" height="4" fill="#1a1a1a"/>) },
  { id:"mineral", name:"Mineral", egs:"Granite · Slate · Cobalt", glyph:(<polygon points="16,6 26,22 6,22" fill="#1a1a1a"/>) },
  { id:"lab", name:"Lab", egs:"Anthropic · Hex · Retool", glyph:(<><circle cx="11" cy="16" r="4" fill="none" stroke="#1a1a1a" strokeWidth="2"/><circle cx="21" cy="16" r="4" fill="none" stroke="#1a1a1a" strokeWidth="2"/></>) },
  { id:"mythic", name:"Mythic", egs:"Atlas · Hermes · Janus", glyph:(<path d="M16 6 L22 16 L16 26 L10 16 Z" fill="#1a1a1a"/>) },
  { id:"civic", name:"Civic", egs:"Bench · Plaza · Common", glyph:(<><rect x="6" y="20" width="20" height="2" fill="#1a1a1a"/><rect x="9" y="10" width="2" height="10" fill="#1a1a1a"/><rect x="21" y="10" width="2" height="10" fill="#1a1a1a"/></>) },
  { id:"wordplay", name:"Wordplay", egs:"Notion · Figma · Loom", glyph:(<><circle cx="12" cy="16" r="5" fill="none" stroke="#1a1a1a" strokeWidth="2"/><circle cx="20" cy="16" r="3" fill="#1a1a1a"/></>) },
  { id:"compound", name:"Compound", egs:"Postmark · Linkfire · Datadog", glyph:(<><rect x="6" y="13" width="9" height="6" fill="#1a1a1a"/><rect x="17" y="13" width="9" height="6" fill="none" stroke="#1a1a1a" strokeWidth="2"/></>) },
  { id:"coined", name:"Coined", egs:"Vercel · Klombic · Resend", glyph:(<text x="16" y="22" fontFamily="JetBrains Mono" fontSize="14" textAnchor="middle" fill="#1a1a1a">⌘</text>) },
];

const TLD_LIST = ["com","io","app","dev","co","ai","xyz","so"];
const USPTO_CLASSES = [
  {id:9,lbl:"9",sub:"Software"},
  {id:35,lbl:"35",sub:"Business"},
  {id:42,lbl:"42",sub:"SaaS"},
  {id:38,lbl:"38",sub:"Telecom"},
];

const PRICING = {
  3:  { price:  9.99, name: "Quick" },
  5:  { price: 13.99, name: "Starter" },
  10: { price: 19.99, name: "Premium" },
};

const StepRail = ({ step, setStep }) => {
  const steps = [
    { n:"00", lbl:"Mode", sub:"Check · generate · mix" },
    { n:"01", lbl:"Constraints", sub:"What must be true" },
    { n:"02", lbl:"Archetype", sub:"What kind of name" },
    { n:"03", lbl:"Candidates", sub:"How many · which" },
    { n:"04", lbl:"Checkout", sub:"Email · pay" },
  ];
  return (
    <div className="steps-rail">
      {steps.map((s, i) => (
        <div key={i}
          className={`step-rail ${step===i?'active':''} ${i<step?'done':''}`}
          onClick={()=>setStep(i)}>
          <span className="num">{i<step ? '✓' : s.n}</span>
          <div>
            <div className="lbl">{s.lbl}</div>
            <div className="sub">{s.sub}</div>
          </div>
        </div>
      ))}
    </div>
  );
};

const StepConstraints = ({ state, setState, next, back }) => {
  const toggleTld = (t) => {
    const tlds = state.tlds.includes(t) ? state.tlds.filter(x=>x!==t) : [...state.tlds, t];
    setState({...state, tlds});
  };
  const shopifyOn = state.markets.includes('shopify');
  const toggleShopify = () => {
    const markets = shopifyOn ? state.markets.filter(x=>x!=='shopify') : [...new Set([...state.markets, 'shopify'])];
    setState({...state, markets});
  };
  return (
    <div>
      <h2>What must be true?</h2>
      <p className="panel-lead">Two knobs in v1 — the TLDs that have to be free and whether to check Shopify. USPTO class, language scan tier, and other-marketplace handles use sensible defaults; we'll expose the dials in v2.</p>

      <div className="field-group">
        <label>Required TLDs · the deal-breakers</label>
        <div className="toggle-grid">
          {TLD_LIST.map(t => {
            const on = state.tlds.includes(t);
            const req = state.requireTlds.includes(t);
            return (
              <button key={t}
                className={`toggle ${on?'on':''} ${on&&req?'req':''}`}
                onClick={()=>toggleTld(t)}
                onContextMenu={(e)=>{
                  e.preventDefault();
                  const requireTlds = state.requireTlds.includes(t) ? state.requireTlds.filter(x=>x!==t) : [...state.requireTlds, t];
                  setState({...state, requireTlds, tlds: state.tlds.includes(t) ? state.tlds : [...state.tlds, t]});
                }}>
                <span>.{t}</span>
                {on && req && <span className="req-tag">REQUIRED</span>}
              </button>
            );
          })}
        </div>
        <p style={{fontSize:12,color:'var(--mute)',marginTop:10,fontFamily:'JetBrains Mono, monospace',letterSpacing:'0.04em'}}>RIGHT-CLICK A TLD TO MARK AS REQUIRED · {state.requireTlds.length} REQUIRED</p>
      </div>

      <div className="field-group">
        <label>Shopify App Store slug check</label>
        <div className="toggle-grid" style={{gridTemplateColumns:'repeat(2,1fr)'}}>
          <button className={`toggle ${shopifyOn?'on':''}`} onClick={toggleShopify}>
            <span>Yes — I'm shipping a Shopify app</span>
            <span style={{fontSize:10,letterSpacing:'0.04em',opacity:0.7}}>Check apps.shopify.com/&lt;slug&gt;</span>
          </button>
          <button className={`toggle ${!shopifyOn?'on':''}`} onClick={toggleShopify}>
            <span>No — skip it</span>
            <span style={{fontSize:10,letterSpacing:'0.04em',opacity:0.7}}>Faster turnaround</span>
          </button>
        </div>
      </div>

      <div className="field-group" style={{borderTop:'1px dashed var(--rule)',paddingTop:18,marginTop:8}}>
        <label style={{color:'var(--mute)'}}>v1 defaults applied · v2 will expose</label>
        <div style={{display:'grid',gridTemplateColumns:'repeat(3,1fr)',gap:8,fontSize:12,color:'var(--mute)',fontFamily:'JetBrains Mono, monospace',letterSpacing:'0.04em'}}>
          <span>USPTO · class 042 (SaaS)</span>
          <span>Languages · Core 7</span>
          <span>Other marketplaces · skipped</span>
        </div>
      </div>

      <div className="order-actions">
        <button className="order-back" onClick={back}>← Back</button>
        <button className="btn btn-primary" onClick={next}>Next · archetype ↗</button>
      </div>
    </div>
  );
};

const StepArchetype = ({ state, setState, next, back }) => (
  <div>
    <h2>What kind of name?</h2>
    <p className="panel-lead">Different archetypes score differently on memorability and sound-symbolism. Pick the closest — this weights your final report, it doesn't filter candidates.</p>
    <div className="archetype-grid">
      {ARCHETYPES.map(a => (
        <button key={a.id}
          className={`arch ${state.archetype===a.id?'on':''}`}
          onClick={()=>setState({...state, archetype:a.id})}>
          <div className="arch-glyph"><svg width="32" height="32" viewBox="0 0 32 32">{a.glyph}</svg></div>
          <span className="arch-name">{a.name}</span>
          <span className="arch-egs">{a.egs}</span>
        </button>
      ))}
    </div>
    <div className="order-actions">
      <button className="order-back" onClick={back}>← Back</button>
      <button className="btn btn-primary" onClick={next} disabled={!state.archetype}>Next · candidates ↗</button>
    </div>
  </div>
);

const StepCandidates = ({ state, setState, next, back }) => {
  const mode = state.mode || 'validate';
  const setCount = (n) => {
    let cands = [...state.candidates];
    while (cands.length < n) cands.push("");
    cands = cands.slice(0, n);
    setState({...state, plan:n, candidates:cands});
  };
  const updateCand = (i, v) => {
    const cs = [...state.candidates]; cs[i] = v; setState({...state, candidates:cs});
  };
  const updateBrief = (v) => setState({...state, brief: v});

  // Mode-specific copy + UI
  const headline = mode==='validate' ? "How many candidates?"
                 : mode==='generate' ? "Tell me about the brand."
                 : "What do you have, and what should I generate?";
  const lede = mode==='validate'
    ? "More names = more chances of finding one that clears every constraint. Each name gets the full six-check pass and a side-by-side comparison page in the report."
    : mode==='generate'
    ? "Two or three sentences is enough. What does the brand do, who is it for, what voice should it land in? I'll generate, screen against your constraints, and deliver the top-N ranked finalists."
    : "Drop in the names you're already considering — leave the rest blank and I'll generate fillers from your brief. Your picks stay in (we surface flags but don't override your call).";

  // Generate mode: no per-name slots; just brief
  // Validate mode: N name inputs, no brief
  // Hybrid: brief + N optional name inputs (blanks become AI suggestions)

  return (
    <div>
      <h2>{headline}</h2>
      <p className="panel-lead">{lede}</p>

      <div className="field-group">
        <label>Plan</label>
        <div className="toggle-grid" style={{gridTemplateColumns:'repeat(3,1fr)'}}>
          {[3,5,10].map(n => (
            <button key={n} className={`toggle ${state.plan===n?'on':''}`} onClick={()=>setCount(n)}>
              <span>{PRICING[n].name} · {n} {mode==='validate'?'candidates':'finalists'}</span>
              <span style={{fontSize:11,letterSpacing:'0.04em',opacity:0.8}}>${PRICING[n].price}</span>
            </button>
          ))}
        </div>
      </div>

      {(mode==='generate' || mode==='hybrid') && (
        <div className="field-group">
          <label>Brand brief · what should we generate against?</label>
          <textarea
            className="text-input"
            style={{minHeight:120, fontFamily:'inherit', resize:'vertical', padding:'14px 16px', fontSize:14, lineHeight:1.5}}
            value={state.brief}
            onChange={(e)=>updateBrief(e.target.value)}
            placeholder="e.g. A B2B SaaS for indie founders. Helps them screen brand names before filing trademarks. Voice: confident, technical, slightly dry — not corporate-legal-tech, not bouncy startup. EN/ES pronounceable."
          />
          <p style={{fontSize:11,color:'var(--mute)',marginTop:6,fontFamily:'JetBrains Mono, monospace',letterSpacing:'0.04em',textTransform:'uppercase'}}>
            {state.brief.trim().split(/\s+/).filter(Boolean).length} WORDS · 30–80 IS THE SWEET SPOT
          </p>
        </div>
      )}

      {(mode==='validate' || mode==='hybrid') && (
        <div className="field-group">
          <label>{mode==='hybrid' ? `Your picks · leave blanks for AI to fill (up to ${state.plan-1} of ${state.plan})` : 'Names to check'}</label>
          <div className="candidates-input">
            {state.candidates.map((c, i) => (
              <div className="cand-row" key={i}>
                <span className="cand-num">{String(i+1).padStart(2,'0')}</span>
                <input
                  value={c}
                  placeholder={mode==='hybrid'
                    ? (i===0 ? "your top pick (or leave blank)" : "another (or leave blank for AI fill)")
                    : (i===0 ? "e.g. klombic" : "another candidate")}
                  onChange={(e)=>updateCand(i, e.target.value)} />
              </div>
            ))}
          </div>
          {mode==='hybrid' && (
            <p style={{fontSize:11,color:'var(--mute)',marginTop:8,fontFamily:'JetBrains Mono, monospace',letterSpacing:'0.04em',textTransform:'uppercase'}}>
              {state.candidates.filter(Boolean).length} OF {state.plan} FILLED · AI WILL FILL {state.plan - state.candidates.filter(Boolean).length}
            </p>
          )}
        </div>
      )}

      <div className="order-actions">
        <button className="order-back" onClick={back}>← Back</button>
        <button
          className="btn btn-primary"
          onClick={next}
          disabled={
            (mode==='generate' && !state.brief.trim()) ||
            (mode==='hybrid'   && (!state.brief.trim() || state.candidates.every(c=>!c.trim()))) ||
            (mode==='validate' && state.candidates.filter(Boolean).length < state.plan)
          }>
          Next · checkout ↗
        </button>
      </div>
    </div>
  );
};

const StepCheckout = ({ state, setState, next, back }) => {
  const tier = PRICING[state.plan];
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState(null);

  const tierKey = tier.name.toLowerCase();  // 'quick' | 'starter' | 'standard'

  const startCheckout = async () => {
    setSubmitting(true); setError(null);
    try {
      const res = await fetch('/api/checkout', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          tier: tierKey,
          mode: state.mode,
          plan: state.plan,
          archetype: state.archetype,
          tlds: state.tlds,
          requireTlds: state.requireTlds,
          shopify: state.markets.includes('shopify'),
          candidates: state.candidates.filter(Boolean),
          brief: state.brief || '',
        }),
      });
      const data = await res.json();
      if (!res.ok) {
        setError(data.error || 'Could not start checkout. Try again or email hello@klombic.com.');
        setSubmitting(false);
        return;
      }
      // Redirect to Stripe-hosted checkout
      window.location.href = data.url;
    } catch (e) {
      setError('Network error. Try again or email hello@klombic.com.');
      setSubmitting(false);
    }
  };

  return (
    <div>
      <h2>Last look — then Stripe.</h2>
      <p className="panel-lead">Confirm the order summary and continue to Stripe checkout. We collect your email there; the report lands in that inbox in ≤ 4 hours.</p>

      <div className="summary-card">
        <div className="sm-row"><span>Mode</span><b>{state.mode || '—'}</b></div>
        <div className="sm-row"><span>Plan</span><b>{tier.name} · {state.plan} candidates</b></div>
        <div className="sm-row"><span>Archetype</span><b>{ARCHETYPES.find(a=>a.id===state.archetype)?.name || '—'}</b></div>
        <div className="sm-row"><span>TLDs · required</span><b>{state.tlds.length} · {state.requireTlds.length} req</b></div>
        <div className="sm-row"><span>Shopify slug check</span><b>{state.markets.includes('shopify') ? 'yes' : 'no'}</b></div>
        <div className="sm-row"><span>Languages</span><b>15 (default)</b></div>
        <div className="sm-row"><span>Turnaround</span><b>≤ 4 hours</b></div>
        <div className="sm-row"><span>14-day re-run</span><b>included</b></div>
        <div className="sm-row" style={{paddingTop:12,borderTop:'1px solid var(--rule-2)'}}>
          <span style={{fontSize:14,color:'var(--ink)'}}>Total · one-time</span>
          <span className="sm-total">${tier.price}</span>
        </div>
      </div>

      {error && (
        <div style={{marginTop:14,padding:'10px 14px',background:'#fde7e6',border:'1px solid #b3261e',borderRadius:4,color:'#a23030',fontSize:13,fontFamily:'JetBrains Mono, monospace',letterSpacing:'0.04em'}}>
          {error}
        </div>
      )}

      <div className="order-actions">
        <button className="order-back" onClick={back} disabled={submitting}>← Back</button>
        <button className="btn btn-primary" onClick={startCheckout} disabled={submitting}>
          {submitting ? 'Starting Stripe…' : `Pay $${tier.price} · continue to Stripe ↗`}
        </button>
      </div>
    </div>
  );
};

const StepConfirm = ({ state, go }) => {
  const tier = PRICING[state.plan];
  return (
    <div className="confirm">
      <div className="check-icon">✓</div>
      <h2>Check is running.</h2>
      <p className="lead" style={{margin:'0 auto'}}>Report #2026-0427-K{Math.floor(Math.random()*99).toString().padStart(2,'0')} will land at <b style={{color:'var(--ink)'}}>{state.email||'your inbox'}</b> within 4 hours.</p>
      <div className="receipt">
        <div className="r-row"><span>Plan</span><b>{tier.name} · ${tier.price}</b></div>
        <div className="r-row"><span>Candidates</span><b>{state.candidates.filter(Boolean).length || state.plan}</b></div>
        <div className="r-row"><span>Archetype</span><b>{ARCHETYPES.find(a=>a.id===state.archetype)?.name || '—'}</b></div>
        <div className="r-row"><span>ETA</span><b>{new Date(Date.now()+4*3600*1000).toLocaleTimeString([],{hour:'2-digit',minute:'2-digit'})} · today</b></div>
      </div>
      <div style={{marginTop:32}}>
        <a className="btn btn-ghost" href="#" onClick={(e)=>{e.preventDefault();go('home')}}>← Back home</a>
      </div>
    </div>
  );
};

// Step 0 — pick a mode. Determines whether we validate user names, generate fresh,
// or hybrid (user provides some, AI fills the rest).
const StepMode = ({ state, setState, next }) => {
  const pick = (mode) => { setState({...state, mode}); next(); };
  return (
    <div>
      <h2>What do you have today?</h2>
      <p className="panel-lead">Klombic does three things — pick the one that fits where you are. Plan size (3 / 5 / 10 candidates) comes later.</p>
      <div className="mode-grid">
        <button className={`mode-card ${state.mode==='validate'?'on':''}`} onClick={()=>pick('validate')}>
          <span className="mode-letter">A</span>
          <h3>I have names</h3>
          <p>You give us 3, 5, or 10 candidate names. We run the six-check pass on each and rank them side-by-side. No generation — pure due diligence on what you bring.</p>
          <span className="mode-fit">Best for: founders with a shortlist, ready to file</span>
        </button>
        <button className={`mode-card ${state.mode==='generate'?'on':''}`} onClick={()=>pick('generate')}>
          <span className="mode-letter">B</span>
          <h3>I need names</h3>
          <p>Describe your brand in 2–3 sentences. We generate candidates against your constraints and deliver the top 3, 5, or 10 ranked finalists.</p>
          <span className="mode-fit">Best for: founders starting from a blank page</span>
        </button>
        <button className={`mode-card ${state.mode==='hybrid'?'on':''}`} onClick={()=>pick('hybrid')}>
          <span className="mode-letter">C</span>
          <h3>A mix</h3>
          <p>You give us 1 to (N−1) names you're considering. We generate the rest from your brief, run everything through the checks, and rank the full set. Your picks stay in — we surface flags but don't override.</p>
          <span className="mode-fit">Best for: founders with a couple ideas + want alternatives</span>
        </button>
      </div>
    </div>
  );
};

const OrderFlow = ({ go }) => {
  const [step, setStep] = React.useState(0);
  const [state, setState] = React.useState({
    mode: null,          // 'validate' | 'generate' | 'hybrid' — set in Step 0
    brief: "",           // 2–3 sentences for generate / hybrid
    tlds: ["com","io","app"],
    requireTlds: ["com"],
    classes: [9,35,42],
    markets: ["shopify"],  // v1: only Shopify exposed; default ON
    langs: "core",
    archetype: "operator",
    plan: 5,
    candidates: ["","","","",""],
    email: "",
  });

  // Confirmation screen lives outside the step rail
  if (step === 5) return <OrderShell step={step} setStep={setStep}><StepConfirm state={state} go={go}/></OrderShell>;

  const next = () => setStep(s => Math.min(5, s+1));
  const back = () => setStep(s => Math.max(0, s-1));

  return (
    <OrderShell step={step} setStep={setStep}>
      {step===0 && <StepMode        state={state} setState={setState} next={next}/>}
      {step===1 && <StepConstraints state={state} setState={setState} next={next} back={back}/>}
      {step===2 && <StepArchetype   state={state} setState={setState} next={next} back={back}/>}
      {step===3 && <StepCandidates  state={state} setState={setState} next={next} back={back}/>}
      {step===4 && <StepCheckout    state={state} setState={setState} next={next} back={back}/>}
    </OrderShell>
  );
};

const OrderShell = ({ step, setStep, children }) => (
  <section className="order">
    <div className="page">
      <div className="section-label">Order</div>
      <h2 style={{marginBottom:48,maxWidth:600}}>Pick your mode. Set constraints. Get a PDF.</h2>
      <div className="order-grid">
        <StepRail step={step} setStep={(i)=>step<5 && setStep(i)}/>
        <div className="order-panel">{children}</div>
      </div>
    </div>
  </section>
);

window.OrderFlow = OrderFlow;
