/* ============================================================
   TECHIYAT — app root (routing, persona, modals)
   ============================================================ */

function RequestModal({ company, kind, onClose, onConfirm }){
  if(!company) return null;
  const isIntro = kind==="intro";
  const steps = isIntro
    ? ["Your request goes to the founder","Founder reviews your profile","Founder approves the introduction","You're connected — confidentially"]
    : ["You agree to confidentiality terms","Identity stays hidden until founder approves","Full profile unlocks once the founder approves","Every view is logged"];
  return (
    <Modal open={!!company} onClose={onClose}
      title={isIntro? "Request introduction" : (company.gated? "Request access" : "Request confidential review")}
      icon={isIntro? "handshake":"lock"}
      footer={<>
        <button className="btn btn-ghost" onClick={onClose}>Cancel</button>
        <button className="btn btn-primary" onClick={onConfirm}><Icon name="check" size={15}/> {isIntro? "Send request":"Agree & request"}</button>
      </>}>
      <div className="row gap12 mb16" style={{padding:"13px 15px", background:"var(--paper-raised)", border:"1px solid var(--line)", borderRadius:11}}>
        <div className="side-mark" style={{width:40,height:40,background:"var(--paper-sunken)",boxShadow:"none",border:"1px solid var(--line)",flex:"none"}}>
          <Icon name={SECTOR_ICON[company.domain]||SECTOR_ICON.default} size={19} style={{color:"var(--pine)"}}/>
        </div>
        <div className="grow"><div className="row gap8"><span className="mono" style={{fontSize:11.5, color:"var(--sage)"}}>{company.code}</span></div>
          <div style={{fontSize:14, fontWeight:600, color:"var(--ink)"}}>{company.title}</div></div>
      </div>
      <p style={{fontSize:13.5, color:"var(--ink-2)", lineHeight:1.55, marginBottom:14}}>
        {isIntro
          ? "Founder approval is required before any introduction. Here's what happens next:"
          : "This company is confidential by design. Here's how access works:"}
      </p>
      <div className="col gap10">
        {steps.map((s,i)=>(
          <div key={i} className="row gap10">
            <span className="step-line" style={{display:"none"}}/>
            <span className="sn" style={{width:24,height:24,borderRadius:"50%",background:"var(--pine)",color:"#fff",display:"grid",placeItems:"center",fontSize:11,fontFamily:"var(--mono)",fontWeight:600,flex:"none"}}>{i+1}</span>
            <span style={{fontSize:13.5, color:"var(--ink-2)"}}>{s}</span>
          </div>
        ))}
      </div>
      <div className="row gap6 mt16" style={{fontSize:11.5, color:"var(--sage)"}}><Icon name="eye" size={13}/> This action is recorded in the audit log.</div>
    </Modal>
  );
}

function OutreachModal({ detected, onClose, onSend }){
  const draftFor = d => `This note is private and comes with zero obligation.\n\nWe noticed a few external signals suggesting the months ahead could get tight — something many strong teams hit. We're reaching out early, quietly, while every option is still open.\n\nIf it's ever useful, Techiyat can help you map a soft landing — preserving your IP, your data, and your team's future, entirely on your terms. Nothing is listed or shared without your say-so.\n\nWhenever you're ready, we're here.`;
  const [msg,setMsg] = useState("");
  const [gen,setGen] = useState(false);
  React.useEffect(()=>{ if(detected) setMsg(draftFor(detected)); },[detected]);
  if(!detected) return null;
  async function regen(){
    if(!(window.claude && window.claude.complete)) return;
    setGen(true);
    try{
      const sys = "You are Techiyat, an Israeli startup-IP preservation platform. Write a short (max 90 words), warm, dignified private outreach note to a founder whose company shows early external distress signals. No obligation, fully confidential, never use the words 'failing' or 'dead'. Emphasize preserving IP, data and team on their terms. Plain text.";
      const out = await window.claude.complete(sys+"\n\nSector: "+detected.sector+". Signals: "+detected.signals.map(s=>s.src+' '+s.label).join('; ')+".\n\nNote:");
      if(out && out.trim()) setMsg(out.trim());
    }catch(e){}
    setGen(false);
  }
  return (
    <Modal open={!!detected} onClose={onClose} wide
      title="Confidential outreach" icon="broadcast"
      footer={<>
        <button className="btn btn-ghost" onClick={onClose}>Cancel</button>
        <button className="btn btn-primary" onClick={onSend}><Icon name="send" size={15}/> Send confidential note</button>
      </>}>
      <div className="row gap12 mb16" style={{padding:"13px 15px", background:"var(--paper-raised)", border:"1px solid var(--line)", borderRadius:11}}>
        <div className="side-mark" style={{width:40,height:40,background:"var(--paper-sunken)",boxShadow:"none",border:"1px solid var(--line)",flex:"none"}}>
          <Icon name={SECTOR_ICON[detected.domain]||SECTOR_ICON.default} size={19} style={{color:"var(--pine)"}}/>
        </div>
        <div className="grow"><div className="row gap8"><span className="mono" style={{fontSize:11.5, color:"var(--sage)"}}>{detected.code}</span><span className="badge info">Detected ~{detected.lead} early</span></div>
          <div style={{fontSize:14, fontWeight:600, color:"var(--ink)"}}>{detected.sector}</div></div>
      </div>
      <div className="field">
        <div className="row between"><label>Private note to the founder</label>
          <button className="btn btn-quiet btn-sm" onClick={regen} disabled={gen}><Icon name="spark" size={13} style={{color:"var(--amber)"}}/> {gen?"Drafting…":"Rewrite with agent"}</button>
        </div>
        <textarea className="textarea" style={{minHeight:170, lineHeight:1.55}} value={msg} onChange={e=>setMsg(e.target.value)}/>
        <span className="hint"><Icon name="shield" size={12} style={{verticalAlign:"-2px"}}/> Sent privately. The founder is never named or listed unless they reply and choose to engage.</span>
      </div>
    </Modal>
  );
}

function App(){
  const [view,setView] = useState("landing");
  const [persona,setPersona] = useState("founder");
  const [heroVariant,setHeroVariant] = useState("split");
  const [company,setCompany] = useState(null);
  const [unlocked,setUnlocked] = useState(false);
  const [req,setReq] = useState(null); // {company, kind}
  const [outreach,setOutreach] = useState(null); // detected company
  const [toastNode,showToast] = useToast();

  function go(v, p){
    if(p) setPersona(p);
    if(v==="profile" && !company) v="opportunities";
    setView(v);
    window.scrollTo(0,0);
    const main = document.querySelector(".main"); if(main) main.scrollTop=0;
  }
  function openProfile(c){ setCompany(c); setUnlocked(false); setView("profile"); window.scrollTo(0,0); }
  function onRequest(c, kind="access"){ setReq({company:c, kind}); }
  function confirmReq(){
    const isIntro = req.kind==="intro";
    showToast(isIntro? "Introduction requested — sent to the founder for approval." : "Access requested — pending founder approval.");
    if(!isIntro && req.company && view==="profile") setUnlocked(true);
    setReq(null);
  }

  // landing is full-bleed
  if(view==="landing"){
    return (<>
      <Landing go={go} variant={heroVariant} setVariant={setHeroVariant}/>
      {toastNode}
    </>);
  }

  let screen;
  switch(view){
    case "dashboard":     screen = <Dashboard persona={persona} setPersona={setPersona} go={go} openProfile={openProfile}/>; break;
    case "opportunities": screen = <Marketplace openProfile={openProfile} onRequest={onRequest}/>; break;
    case "matches":       screen = <Buyer openProfile={openProfile} onRequest={onRequest} go={go} toast={showToast}/>; break;
    case "portfolio":     screen = <Investor openProfile={openProfile} go={go}/>; break;
    case "signals":       screen = <Signals onOutreach={setOutreach} openProfile={openProfile} go={go}/>; break;
    case "founder":       screen = <FounderFlow go={go} toast={showToast}/>; break;
    case "ecosystem":     screen = <Ecosystem go={go}/>; break;
    case "agent":         screen = <Agent toast={showToast} go={go}/>; break;
    case "trust":         screen = <Trust go={go}/>; break;
    case "settings":      screen = <Settings/>; break;
    case "profile":       screen = <Profile c={company} go={go} onRequest={c=>onRequest(c,"intro")} unlocked={unlocked}/>; break;
    default:              screen = <Dashboard persona={persona} setPersona={setPersona} go={go} openProfile={openProfile}/>;
  }

  const wide = view==="agent";
  return (
    <AppShell view={view} go={go} persona={persona} setPersona={setPersona} openProfile={openProfile} wide={wide}>
      {screen}
      <RequestModal company={req?.company} kind={req?.kind} onClose={()=>setReq(null)} onConfirm={confirmReq}/>
      <OutreachModal detected={outreach} onClose={()=>setOutreach(null)} onSend={()=>{ showToast("Confidential note sent — no obligation, founder-controlled."); setOutreach(null); }}/>
      {toastNode}
    </AppShell>
  );
}

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