/* ============================================================
   TECHIYAT — intelligence agent (live + scripted fallback)
   ============================================================ */

const AGENT_PROMPTS = [
  "Find Israeli medtech companies with diagnostics IP and less than 12 months runway.",
  "Show companies with Israel Innovation Authority grants that may need a soft landing.",
  "Match this cybersecurity company to potential acquirers.",
  "Identify companies where the team is more valuable than the product.",
  "Generate an anonymous buyer-facing listing from this founder intake.",
  "Summarize this company's IP in language suitable for strategic buyers.",
  "Suggest likely buyer categories for this medical imaging team.",
  "Flag grant obligations that might affect an IP sale."
];

const PRIVACY = [
  { k:"anon", t:"Generate anonymous listing", on:true },
  { k:"reveal", t:"Reveal identity only after approval", on:true },
  { k:"approval", t:"Require founder approval before full profile", on:true },
  { k:"approve", t:"Founder approval required before intro", on:true },
  { k:"noshare", t:"Do not share externally", on:false }
];

// scripted fallbacks keyed by intent
function scriptedReply(text){
  const t = text.toLowerCase();
  if(t.includes("diagnostics")||t.includes("medtech")&&t.includes("runway")){
    return { body:[
      "I found **2 strong matches** in diagnostics with under 12 months of runway. Both are anonymized and access-controlled:",
      "• **TX-4471** — AI diagnostics platform · 3 granted patents, clinical validation data · 4 mo runway · preservation 86\n• **TX-2210** — Medical-imaging AI · 2 granted patents, annotated dataset · 6 mo runway · preservation 83",
      "Reasoning: both have defensible IP (granted patents), regulated clinical data, and active buyer demand in your sector. Neither identity is revealed until the founder approves.",
    ], chips:["View TX-4471","View TX-2210"], note:"Nothing shared — these are confidential matches surfaced only to you." };
  }
  if(t.includes("grant")||t.includes("innovation authority")||t.includes("soft landing")){
    return { body:[
      "**3 IIA grant-backed companies** show soft-landing signals right now:",
      "• **TX-4471** (Diagnostics) — grant reporting overdue, 4 mo runway, IP-retention clause active\n• **TX-5108** (Cybersecurity) — reporting current, 5 mo runway\n• **TX-6033** (Agritech) — wind-down notice filed, hardware IP at risk",
      "I'd prioritize TX-4471: highest preservation score and a grant clause that needs clearing before any IP transfer. Want me to draft outreach?",
    ], chips:["Open ecosystem view","Draft founder outreach"], note:"Grant obligations are flagged but identities stay coded." };
  }
  if(t.includes("acquirer")||t.includes("match")&&t.includes("cyber")){
    return { body:[
      "For the cybersecurity automation engine (**TX-5108**), the strongest acquirer categories are:",
      "• **Cloud security companies** — detection models complement existing platforms\n• **MDR providers** — enterprise pilots + senior detection team are immediately useful\n• **Enterprise security platforms** — acqui-hire of the engineering bench",
      "This reads as a **team-led, acqui-hire** opportunity — the senior detection engineers may be more valuable than the standalone product.",
    ], chips:["View TX-5108","Generate listing"], note:"Match reasoning shown for your review before any intro is requested." };
  }
  if(t.includes("team is more valuable")||t.includes("acqui")&&t.includes("team")){
    return { body:[
      "**2 opportunities** read as team-first (talent > product):",
      "• **TX-7781** — Inference-optimization infra · 6-person senior infra team · thin GTM\n• **TX-5108** — Cybersecurity · 9 senior detection engineers · pilot-stage product",
      "In both, I'd frame the deal as an **acqui-hire with IP assignment** rather than a product acquisition.",
    ], chips:["View TX-7781","View TX-5108"], note:"Surfaced for preservation — keeping these teams in the ecosystem." };
  }
  if(t.includes("listing")){
    return { listing:true, body:[
      "Here's a **draft anonymous buyer-facing listing** generated from the NegevDx intake. Nothing is published until you approve it.",
    ], note:"Draft only · founder approval required before this goes live." };
  }
  if(t.includes("summarize")&&t.includes("ip")){
    return { body:[
      "**IP summary — strategic-buyer framing (TX-4471):**",
      "A production-grade AI diagnostics pipeline protected by **3 granted patents** (2 pending), validated on clinical data from four medical centers, and **CE-marked**. The defensible moat is the combination of regulatory clearance, proprietary clinical data, and computer-vision models — difficult to replicate from scratch.",
      "Suggested positioning: *\"Regulatory-cleared diagnostic AI with validated clinical evidence and a patent family — a build-vs-buy accelerator of 18–24 months for an imaging or diagnostics acquirer.\"*",
    ], chips:["Use in listing","View full profile"], note:"Language reviewed for buyer audience — approve before sharing." };
  }
  if(t.includes("buyer categor")||t.includes("imaging")){
    return { body:[
      "For the medical-imaging team (**TX-2210**), likely buyer categories:",
      "• **Imaging vendors** (modality OEMs adding AI triage)\n• **Radiology platforms** (workflow + reading tools)\n• **Hospital networks** (in-house diagnostic AI)",
      "The team's **computer-vision + regulatory** mix is the standout asset — strong acqui-hire fit even beyond the product.",
    ], chips:["View TX-2210"], note:"Recommendations only · founder controls outreach." };
  }
  if(t.includes("grant obligation")||t.includes("affect an ip sale")){
    return { body:[
      "**Grant obligations that could affect an IP sale:**",
      "• **IP-retention clause** — IIA-funded IP generally must stay in Israel; offshore transfer may trigger consent + repayment.\n• **Royalty/repayment** — outstanding grant balance can be due on a sale or IP transfer.\n• **Notification** — the Authority typically must be notified before a material IP transaction.",
      "I'd recommend structuring as an **in-Israel acquisition or license** to stay clause-compliant. Want me to flag this on the company profile?",
    ], chips:["Open ecosystem view","Flag on profile"], note:"Compliance guidance — not legal advice." };
  }
  return { body:[
    "I can help you search, summarize, anonymize, and match across the ecosystem — always with founder approval before anything is shared.",
    "Try asking me to find companies by sector and runway, generate an anonymous listing, summarize a company's IP for buyers, or flag grant obligations.",
  ], note:"I explain my reasoning and never share externally without approval." };
}

function ListingCard({ onApprove, approved }){
  const c = window.TZ.COMPANIES[0];
  return (
    <div className="card mt8" style={{overflow:"hidden", borderColor:"var(--amber-line)"}}>
      <div className="row between" style={{padding:"12px 16px", background:"var(--amber-bg)", borderBottom:"1px solid var(--amber-line)"}}>
        <span className="row gap8" style={{fontSize:12.5, fontWeight:600, color:"var(--amber)"}}><Icon name="eyeOff" size={14}/> Draft anonymous listing</span>
        <span className="mono" style={{fontSize:11, color:"var(--amber)"}}>{c.code}</span>
      </div>
      <div className="card-pad" style={{padding:16}}>
        <h3 style={{fontSize:15.5}}>{c.title}</h3>
        <div className="row gap6 wrap mt8 mb12">{c.assets.slice(0,4).map(a=><span key={a} className="tag" style={{fontSize:11.5}}>{a}</span>)}</div>
        <p style={{fontSize:13, color:"var(--ink-2)", lineHeight:1.5}}>{c.blurb}</p>
        <div className="row gap14 mt12" style={{fontSize:12, color:"var(--sage)"}}>
          <span>Sector: {c.sector}</span><span>Team: {c.team}</span><span>Location: Israel</span>
        </div>
      </div>
      <div className="row between" style={{padding:"12px 16px", borderTop:"1px solid var(--line)", background:"var(--paper-raised)"}}>
        <span className="muted" style={{fontSize:12}}>{approved? "Approved · ready for verified buyers" : "Identity hidden · approve to publish"}</span>
        {approved ? <span className="chip green"><Icon name="check" size={13}/> Approved</span>
          : <button className="btn btn-amber btn-sm" onClick={onApprove}><Icon name="check" size={14}/> Approve listing</button>}
      </div>
    </div>
  );
}

function Agent({ toast, go }){
  const [msgs,setMsgs] = useState([
    { who:"bot", body:["Shalom — I'm the **Techiyat Intelligence Agent**. I help you search, summarize, anonymize, and match companies across the ecosystem.","Ask me anything, or pick a starter on the right. I'll always explain my reasoning, and nothing is shared externally without approval."], note:"Confidential · founder-approval enforced." }
  ]);
  const [input,setInput] = useState("");
  const [busy,setBusy] = useState(false);
  const [priv,setPriv] = useState(PRIVACY);
  const [approved,setApproved] = useState(false);
  const scrollRef = useRef(null);

  useEffect(()=>{ const el=scrollRef.current; if(el) el.scrollTop=el.scrollHeight; },[msgs,busy]);

  async function send(text){
    const q = (text ?? input).trim();
    if(!q || busy) return;
    setInput("");
    setMsgs(m=>[...m, { who:"user", body:[q] }]);
    setBusy(true);

    const scripted = scriptedReply(q);
    // try live model for free-form questions; use scripted structure if it looks like a known intent
    let reply = scripted;
    const known = AGENT_PROMPTS.some(p=>p.toLowerCase().slice(0,18)===q.toLowerCase().slice(0,18));
    if(!known && window.claude && window.claude.complete){
      try{
        const sys = "You are the Techiyat Intelligence Agent for an Israeli startup-IP preservation platform. Tone: discreet, warm, business-like. Never use 'failed' or 'dead company'; use 'at-risk', 'soft landing', 'second-life opportunity', 'preservation'. Be concise (max ~110 words), explain your reasoning briefly, and remind that nothing is shared without founder approval. Use plain text with short bullet lines.";
        const out = await Promise.race([
          window.claude.complete(sys+"\n\nUser: "+q+"\n\nAgent:"),
          new Promise((_,rej)=>setTimeout(()=>rej("t"),9000))
        ]);
        if(out && out.trim()) reply = { body:[out.trim()], note:scripted.note };
      }catch(e){ /* fall back to scripted */ }
    }
    setBusy(false);
    setMsgs(m=>[...m, { who:"bot", ...reply }]);
  }

  function md(s){
    // tiny markdown: **bold** and newlines
    const parts = s.split(/(\*\*[^*]+\*\*|\*[^*]+\*)/g);
    return parts.map((p,i)=>{
      if(/^\*\*[^*]+\*\*$/.test(p)) return <b key={i}>{p.slice(2,-2)}</b>;
      if(/^\*[^*]+\*$/.test(p)) return <em key={i}>{p.slice(1,-1)}</em>;
      return <React.Fragment key={i}>{p}</React.Fragment>;
    });
  }

  return (
    <div className="fadein">
      <PageHd eyebrow="Preservation & matching assistant"
        title="Techiyat Intelligence Agent"
        sub="Search, summarize, anonymize, and match — with reasoning you can review and approve before anything leaves the platform.">
        <span className="chip green"><span className="chip-dot"/> Online</span>
      </PageHd>

      <div className="agent-wrap">
        <div className="chat">
          <div className="chat-scroll" ref={scrollRef}>
            {msgs.map((m,i)=>(
              <div key={i} className={"msg "+m.who}>
                <div className="mav">{m.who==="bot"? <Icon name="spark" size={16} style={{color:"#fff"}}/> : <Icon name="user" size={15} style={{color:"#fff"}}/>}</div>
                <div className="mbody">
                  {m.body.map((b,j)=><p key={j} style={{whiteSpace:"pre-wrap"}}>{md(b)}</p>)}
                  {m.listing && <ListingCard approved={approved} onApprove={()=>{ setApproved(true); toast("Anonymous listing approved & published to verified buyers."); }}/>}
                  {m.chips && <div className="row gap8 wrap mt12">{m.chips.map(c=>(
                    <button key={c} className="chip" style={{cursor:"pointer"}} onClick={()=>{
                      if(c.startsWith("View")) go("opportunities");
                      else if(c.includes("ecosystem")) go("ecosystem");
                      else if(c.includes("listing")||c.includes("Use in")) send("Generate an anonymous buyer-facing listing from this founder intake.");
                      else toast("Action queued — pending founder approval.");
                    }}>{c} <Icon name="arrowRight" size={12}/></button>
                  ))}</div>}
                  {m.note && <div className="row gap6 mt12" style={{fontSize:11.5, color:"var(--sage)", borderTop:"1px solid var(--line)", paddingTop:8}}><Icon name="lock" size={12}/> {m.note}</div>}
                </div>
              </div>
            ))}
            {busy && <div className="msg bot"><div className="mav"><Icon name="spark" size={16} style={{color:"#fff"}}/></div><div className="mbody"><span className="typing"><i/><i/><i/></span></div></div>}
          </div>
          <div className="chat-input">
            <textarea rows={1} placeholder="Ask the agent to find, summarize, anonymize, or match…" value={input}
              onChange={e=>setInput(e.target.value)}
              onKeyDown={e=>{ if(e.key==="Enter"&&!e.shiftKey){ e.preventDefault(); send(); } }}/>
            <button className="btn btn-primary" style={{padding:"10px 14px"}} onClick={()=>send()} disabled={busy}><Icon name="send" size={16}/></button>
          </div>
        </div>

        {/* right rail */}
        <div className="col gap18" style={{overflowY:"auto"}}>
          <div className="card card-pad">
            <div className="eyebrow mb12">Starter prompts</div>
            <div className="suggest">
              {AGENT_PROMPTS.slice(0,5).map(p=><button key={p} onClick={()=>send(p)}>{p}</button>)}
            </div>
          </div>
          <div className="card card-pad">
            <div className="eyebrow mb12">Privacy controls</div>
            <div className="col gap4">
              {priv.map(p=>(
                <button key={p.k} className="row between" onClick={()=>setPriv(s=>s.map(x=>x.k===p.k?{...x,on:!x.on}:x))}
                  style={{background:"none", border:"none", padding:"9px 2px", cursor:"pointer", textAlign:"left"}}>
                  <span style={{fontSize:13, color:"var(--ink-2)", flex:1}}>{p.t}</span>
                  <span style={{width:36, height:20, borderRadius:20, background:p.on?"var(--moss)":"var(--line-strong)", position:"relative", transition:".18s", flex:"none"}}>
                    <span style={{position:"absolute", top:2, left:p.on?18:2, width:16, height:16, borderRadius:"50%", background:"#fff", transition:".18s", boxShadow:"var(--shadow-sm)"}}/>
                  </span>
                </button>
              ))}
            </div>
            <div className="row gap6 mt12" style={{fontSize:11.5, color:"var(--sage)"}}><Icon name="shield" size={13}/> The agent assists — it never shares without your approval.</div>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Agent });
