/* ============================================================
   TECHIYAT — founder confidential assessment + readiness score
   ============================================================ */

function Choice({ sel, onClick, children, radio }){
  return (
    <button className={"choice"+(radio?" rad":"")+(sel?" sel":"")} onClick={onClick}>
      <span className="ck">{sel && <Icon name="check" size={12} sw={2.6}/>}</span>
      <span className="grow" style={{textAlign:"left"}}>{children}</span>
    </button>
  );
}

const FOUNDER_STEPS = ["Company","Status & assets","Outcome & privacy","Readiness"];

function FounderFlow({ go, toast }){
  const T = window.TZ;
  const [step,setStep] = useState(0);
  const [scoreVariant,setScoreVariant] = useState("seal");
  const [f,setF] = useState({
    name:"NegevDx", sector:"Diagnostics / HealthTech", stage:"Series A", funding:"$8.5M", runway:4,
    team:12, location:"Be'er Sheva", grant:true, investors:"Jordan Valley Ventures, Negev Angels",
    status:"Less than 12 months runway",
    assets:["Patents","Software / IP","Clinical data","Regulatory approvals","Team / acqui-hire"],
    outcome:["IP sale","Strategic acquisition","Acqui-hire"],
    confid:"Visible only after approval"
  });
  const set = (k,v)=> setF(s=>({...s,[k]:v}));
  const toggle = (k,v)=> setF(s=>({...s,[k]: s[k].includes(v)? s[k].filter(x=>x!==v) : [...s[k],v]}));

  // readiness score (positive framing)
  const score = (()=>{
    let s = 52;
    s += Math.min(f.assets.length,7)*4;          // more preservable assets = higher
    if(f.assets.includes("Patents")) s+=5;
    if(f.assets.includes("Regulatory approvals")) s+=4;
    if(f.assets.includes("Clinical data")||f.assets.includes("Dataset")) s+=4;
    if(f.grant) s+=3;
    if(f.runway>=6) s+=4; else if(f.runway<=3) s-=3;
    if(f.outcome.length>=2) s+=3;
    return Math.max(46, Math.min(94, Math.round(s)));
  })();

  const breakdown = [
    { k:"Asset quality", v: Math.min(96, 60+f.assets.length*5), note:`${f.assets.length} preservable asset types` },
    { k:"IP defensibility", v: f.assets.includes("Patents")? 88 : 62, note: f.assets.includes("Patents")? "Patents in inventory" : "No patents listed" },
    { k:"Buyer demand", v: 84, note:"Active buyers in your sector" },
    { k:"Team transferability", v: f.assets.includes("Team / acqui-hire")? 90 : 64, note: f.assets.includes("Team / acqui-hire")? "Team open to acqui-hire":"Team not flagged" },
    { k:"Timing", v: f.runway>=6? 80 : f.runway>=4? 66 : 54, note:`${f.runway} months runway` }
  ];

  const band = score>=80? "strong" : score>=64? "solid" : "early";
  const bandCopy = {
    strong:{ t:"Your company has strong preservation potential.", c:"var(--moss)" },
    solid:{ t:"Your company has solid preservation potential.", c:"var(--amber)" },
    early:{ t:"Your company has emerging preservation potential.", c:"var(--amber)" }
  }[band];

  const actions = [
    { ic:"eyeOff", t:"Create anonymous buyer-facing listing", d:"The agent drafts it from this intake — you approve before anything goes live." },
    { ic:"file", t:"Prepare IP inventory", d:"Patents, code, datasets, and regulatory assets, organized for diligence." },
    { ic:"flag", t:"Map grant obligations", d:"Clarify IIA retention clauses that could affect an IP sale." },
    { ic:"target", t:"Identify likely strategic buyers", d:"We see active demand in diagnostics and medical imaging." },
    { ic:"handshake", t:"Start confidential buyer/investor matching", d:"Founder-approved introductions only." }
  ];

  function next(){ setStep(s=>Math.min(s+1,3)); }
  function back(){ setStep(s=>Math.max(s-1,0)); }

  return (
    <div className="fadein">
      <PageHd eyebrow="Confidential · founder-controlled"
        title="Confidential assessment"
        sub="Privately tell us about your company and assets. Nothing is shared, listed, or revealed without your explicit approval.">
        <span className="chip"><Icon name="lock" size={13}/> Encrypted intake</span>
      </PageHd>

      {/* stepper */}
      <div className="card card-pad mb24" style={{padding:"16px 22px"}}>
        <div className="steps" style={{flexWrap:"wrap", rowGap:10}}>
          {FOUNDER_STEPS.map((s,i)=>(
            <React.Fragment key={s}>
              <div className={"step "+(i<step?"done":i===step?"curr":"")}>
                <span className="sn">{i<step? <Icon name="check" size={13} sw={2.6}/> : i+1}</span>
                <span className="st">{s}</span>
              </div>
              {i<FOUNDER_STEPS.length-1 && <span className={"step-line"+(i<step?" done":"")}/>}
            </React.Fragment>
          ))}
        </div>
      </div>

      {step===0 && (
        <div className="grid" style={{gridTemplateColumns:"1fr 1fr", gap:18}}>
          <div className="card card-pad col gap18">
            <div className="field"><label>Company name</label><input className="input" value={f.name} onChange={e=>set("name",e.target.value)}/><span className="hint">Stored privately — never shown without your consent.</span></div>
            <div className="grid g2">
              <div className="field"><label>Sector</label>
                <select className="select" value={f.sector} onChange={e=>set("sector",e.target.value)}>{T.SECTORS.map(s=><option key={s}>{s}</option>)}</select></div>
              <div className="field"><label>Stage</label>
                <select className="select" value={f.stage} onChange={e=>set("stage",e.target.value)}>{T.STAGES.map(s=><option key={s}>{s}</option>)}</select></div>
            </div>
            <div className="grid g2">
              <div className="field"><label>Funding raised</label><input className="input" value={f.funding} onChange={e=>set("funding",e.target.value)}/></div>
              <div className="field"><label>Team size</label><input className="input" type="number" value={f.team} onChange={e=>set("team",+e.target.value)}/></div>
            </div>
          </div>
          <div className="card card-pad col gap18">
            <div className="field">
              <label>Current runway — <b>{f.runway} months</b></label>
              <input type="range" min="0" max="24" value={f.runway} onChange={e=>set("runway",+e.target.value)} style={{accentColor:"var(--moss)"}}/>
              <span className="hint">This stays private and is only used to time recommendations.</span>
            </div>
            <div className="field"><label>Location</label><input className="input" value={f.location} onChange={e=>set("location",e.target.value)}/></div>
            <div className="field"><label>Existing investors</label><input className="input" value={f.investors} onChange={e=>set("investors",e.target.value)}/></div>
            <div className="field"><label>Israel Innovation Authority grants?</label>
              <div className="row gap10">
                <Choice radio sel={f.grant===true} onClick={()=>set("grant",true)}>Yes</Choice>
                <Choice radio sel={f.grant===false} onClick={()=>set("grant",false)}>No</Choice>
              </div>
            </div>
          </div>
        </div>
      )}

      {step===1 && (
        <div className="grid" style={{gridTemplateColumns:"1fr 1fr", gap:18}}>
          <div className="card card-pad">
            <div className="field mb16"><label style={{fontSize:14.5}}>Current status</label><span className="hint">Honest framing helps us recommend the right path. No status is a failure.</span></div>
            <div className="col gap8">{T.STATUSES.map(s=><Choice key={s} radio sel={f.status===s} onClick={()=>set("status",s)}>{s}</Choice>)}</div>
          </div>
          <div className="card card-pad">
            <div className="field mb16"><label style={{fontSize:14.5}}>Assets available for preservation</label><span className="hint">Select everything valuable that could find a second home.</span></div>
            <div className="grid g2" style={{gap:8}}>{T.ASSETS.map(a=><Choice key={a} sel={f.assets.includes(a)} onClick={()=>toggle("assets",a)}>{a}</Choice>)}</div>
          </div>
        </div>
      )}

      {step===2 && (
        <div className="grid" style={{gridTemplateColumns:"1fr 1fr", gap:18}}>
          <div className="card card-pad">
            <div className="field mb16"><label style={{fontSize:14.5}}>Desired outcome</label><span className="hint">Pick all paths you'd consider. You can change these anytime.</span></div>
            <div className="grid g2" style={{gap:8}}>{T.OUTCOMES.map(o=><Choice key={o} sel={f.outcome.includes(o)} onClick={()=>toggle("outcome",o)}>{o}</Choice>)}</div>
          </div>
          <div className="card card-pad">
            <div className="field mb16"><label style={{fontSize:14.5}}>Confidentiality level</label><span className="hint">You control exactly what buyers can see, and when.</span></div>
            <div className="col gap8">{T.CONFID.map(c=>(
              <button key={c.t} className={"choice rad"+(f.confid===c.t?" sel":"")} onClick={()=>set("confid",c.t)} style={{alignItems:"flex-start"}}>
                <span className="ck" style={{marginTop:2}}>{f.confid===c.t && <Icon name="check" size={12} sw={2.6}/>}</span>
                <span className="col grow" style={{textAlign:"left", gap:2}}>
                  <span style={{fontWeight:600, color:"var(--ink)"}}>{c.t}</span>
                  <span style={{fontSize:12.5, color:"var(--sage)", fontWeight:400}}>{c.d}</span>
                </span>
              </button>
            ))}</div>
          </div>
        </div>
      )}

      {step===3 && (
        <ReadinessResult f={f} score={score} band={band} bandCopy={bandCopy} breakdown={breakdown}
          actions={actions} variant={scoreVariant} setVariant={setScoreVariant} go={go} toast={toast}/>
      )}

      {step<3 && (
        <div className="row between mt24">
          <button className="btn btn-ghost" onClick={step===0? ()=>go("landing") : back}>
            <Icon name="arrowRight" size={15} style={{transform:"rotate(180deg)"}}/> {step===0? "Cancel":"Back"}
          </button>
          <div className="row gap10">
            <span className="muted" style={{fontSize:13}}>Step {step+1} of 4</span>
            <button className="btn btn-primary" onClick={next}>{step===2? "Calculate readiness score":"Continue"} <Icon name="arrowRight" size={15}/></button>
          </div>
        </div>
      )}
    </div>
  );
}

/* ---- Readiness result with 3 score-treatment variants ---- */
function ReadinessResult({ f, score, band, bandCopy, breakdown, actions, variant, setVariant, go, toast }){
  return (
    <div className="fadein">
      <div className="row between wrap mb16" style={{gap:12}}>
        <div className="chip green"><Icon name="checkCircle" size={14}/> Assessment complete · confidential</div>
        <div className="row gap6" style={{background:"var(--paper-card)", border:"1px solid var(--line-2)", borderRadius:24, padding:4}}>
          <span className="eyebrow" style={{padding:"0 8px", alignSelf:"center"}}>Treatment</span>
          {[["seal","Passport"],["ring","Ring"],["bars","Breakdown"]].map(([k,l])=>(
            <button key={k} className="btn btn-sm" onClick={()=>setVariant(k)}
              style={{borderRadius:20, padding:"6px 12px", background:variant===k?"var(--pine)":"transparent", color:variant===k?"#fff":"var(--sage)", fontSize:12.5}}>{l}</button>
          ))}
        </div>
      </div>

      {variant==="seal" && <ScoreSeal f={f} score={score} bandCopy={bandCopy} breakdown={breakdown}/>}
      {variant==="ring" && <ScoreRingView f={f} score={score} bandCopy={bandCopy} breakdown={breakdown}/>}
      {variant==="bars" && <ScoreBars f={f} score={score} bandCopy={bandCopy} breakdown={breakdown}/>}

      {/* recommended actions */}
      <div className="card mt24" style={{overflow:"hidden"}}>
        <div className="card-hd"><Icon name="bolt" size={17} style={{color:"var(--amber)"}}/><h3 className="serif" style={{fontSize:17}}>Recommended preservation steps</h3></div>
        <div>
          {actions.map((a,i)=>(
            <div key={a.t} className="row gap14" style={{padding:"16px 20px", borderTop:i?"1px solid var(--line)":"none"}}>
              <div className="side-mark" style={{width:38,height:38,background:"var(--paper-sunken)",boxShadow:"none",border:"1px solid var(--line)",flex:"none"}}>
                <Icon name={a.ic} size={18} style={{color:"var(--pine)"}}/>
              </div>
              <div className="grow">
                <div style={{fontSize:14.5, fontWeight:600, color:"var(--ink)"}}>{a.t}</div>
                <div style={{fontSize:13, color:"var(--sage)"}}>{a.d}</div>
              </div>
              <span className="mono" style={{fontSize:11, color:"var(--sage-2)"}}>0{i+1}</span>
            </div>
          ))}
        </div>
        <div className="row between wrap" style={{padding:"16px 20px", borderTop:"1px solid var(--line)", background:"var(--paper-raised)", gap:12}}>
          <span className="muted" style={{fontSize:13}}><Icon name="lock" size={13} style={{verticalAlign:"-2px"}}/> Nothing is shared until you approve each step.</span>
          <div className="row gap10">
            <button className="btn btn-ghost" onClick={()=>go("agent")}><Icon name="spark" size={15} style={{color:"var(--amber)"}}/> Draft my anonymous listing</button>
            <button className="btn btn-primary" onClick={()=>{ toast("Confidential matching started — buyers will request access."); go("opportunities","buyer"); }}>Start confidential matching <Icon name="arrowRight" size={15}/></button>
          </div>
        </div>
      </div>
    </div>
  );
}

function ResultAside({ f, bandCopy }){
  return (
    <div className="col gap14" style={{maxWidth:330}}>
      <h2 className="serif" style={{fontSize:24, lineHeight:1.18, color:bandCopy.c}}>{bandCopy.t}</h2>
      <p style={{fontSize:14.5, color:"var(--ink-2)", lineHeight:1.55}}>
        This reflects how ready <b>{f.name}</b> is for preservation, matching, and a soft landing — not a judgment of the company.
      </p>
      <div className="row gap8 wrap">
        {f.assets.slice(0,4).map(a=><span key={a} className="tag">{a}</span>)}
        {f.assets.length>4 && <span className="tag">+{f.assets.length-4}</span>}
      </div>
    </div>
  );
}

/* Variant 1: passport / seal */
function ScoreSeal({ f, score, bandCopy, breakdown }){
  return (
    <div className="card" style={{overflow:"hidden", background:"linear-gradient(160deg,var(--paper-raised),var(--paper-card))"}}>
      <div style={{display:"grid", gridTemplateColumns:"300px 1fr", gap:0}}>
        <div className="col" style={{alignItems:"center", justifyContent:"center", gap:14, padding:"34px", borderRight:"1px solid var(--line)", textAlign:"center", position:"relative"}}>
          <div className="eyebrow">Techiyat Readiness</div>
          <div style={{position:"relative", width:180, height:180, display:"grid", placeItems:"center"}}>
            <svg viewBox="0 0 180 180" style={{position:"absolute", inset:0}}>
              {[84,72].map((r,i)=><circle key={i} cx="90" cy="90" r={r} fill="none" stroke={i?"var(--amber-line)":"var(--line-2)"} strokeWidth="1" strokeDasharray={i?"2 6":"none"}/>)}
              <circle cx="90" cy="90" r="60" fill="var(--pine)"/>
            </svg>
            <div style={{position:"relative", color:"#fff"}}>
              <div className="serif" style={{fontSize:52, fontWeight:600, lineHeight:1}}>{score}</div>
              <div className="mono" style={{fontSize:9.5, letterSpacing:".14em", opacity:.7}}>OUT OF 100</div>
            </div>
          </div>
          <div className="heb" style={{fontSize:15, color:"var(--amber)"}}>תחיית · second life</div>
          <div className="mono" style={{fontSize:10.5, color:"var(--sage-2)"}}>ISSUED · CONFIDENTIAL · {f.location.toUpperCase()}</div>
        </div>
        <div className="card-pad col gap18" style={{justifyContent:"center"}}>
          <ResultAside f={f} bandCopy={bandCopy}/>
          <div className="grid g2" style={{gap:10}}>
            {breakdown.slice(0,4).map(b=>(
              <div key={b.k} style={{padding:"12px 14px", background:"var(--paper-card)", border:"1px solid var(--line)", borderRadius:10}}>
                <div className="row between mb8"><span style={{fontSize:12.5,fontWeight:600,color:"var(--ink)"}}>{b.k}</span><span className="mono" style={{fontSize:12,color:"var(--pine)"}}>{b.v}</span></div>
                <Meter value={b.v} tone={b.v>=80?"":"amber"} thin/>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

/* Variant 2: ring */
function ScoreRingView({ f, score, bandCopy, breakdown }){
  return (
    <div className="card card-pad">
      <div style={{display:"grid", gridTemplateColumns:"auto 1fr", gap:36, alignItems:"center"}}>
        <div className="col" style={{alignItems:"center", gap:10}}>
          <ScoreRing value={score} size={208} lg label="Readiness"/>
          <span className="heb" style={{fontSize:14, color:"var(--amber)"}}>תחיית · second life</span>
        </div>
        <div className="col gap18">
          <ResultAside f={f} bandCopy={bandCopy}/>
          <div className="col gap12">
            {breakdown.map(b=>(
              <div key={b.k}>
                <div className="row between mb4"><span style={{fontSize:13,fontWeight:500,color:"var(--ink)"}}>{b.k}</span><span className="mono muted" style={{fontSize:11.5}}>{b.note}</span></div>
                <Meter value={b.v} tone={b.v>=80?"":"amber"} thin/>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

/* Variant 3: breakdown bars */
function ScoreBars({ f, score, bandCopy, breakdown }){
  return (
    <div className="grid" style={{gridTemplateColumns:"320px 1fr", gap:18}}>
      <div className="card card-pad col" style={{justifyContent:"center", gap:16, background:"var(--pine)", color:"#fff"}}>
        <div className="eyebrow" style={{color:"var(--amber-2)"}}>Techiyat Readiness</div>
        <div className="serif" style={{fontSize:84, fontWeight:600, lineHeight:.9, color:"#fff"}}>{score}<span style={{fontSize:28, color:"rgba(255,255,255,.5)"}}>/100</span></div>
        <h2 className="serif" style={{fontSize:21, color:"#fff", lineHeight:1.2}}>{bandCopy.t}</h2>
        <p style={{fontSize:13.5, color:"rgba(238,243,239,.7)", lineHeight:1.5}}>Measures readiness for preservation and soft-landing — not company failure.</p>
        <div className="heb" style={{fontSize:15, color:"var(--amber-2)"}}>תחיית המתים</div>
      </div>
      <div className="card card-pad col gap16" style={{justifyContent:"center"}}>
        {breakdown.map(b=>(
          <div key={b.k}>
            <div className="row between mb6">
              <span style={{fontSize:14, fontWeight:600, color:"var(--ink)"}}>{b.k}</span>
              <span className="row gap8"><span className="mono muted" style={{fontSize:12}}>{b.note}</span><span className="mono" style={{fontSize:13, fontWeight:600, color:b.v>=80?"var(--moss)":"var(--amber)"}}>{b.v}</span></span>
            </div>
            <Meter value={b.v} tone={b.v>=80?"":"amber"}/>
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { FounderFlow, Choice });
