/* ============================================================
   TECHIYAT — Signal Radar (proactive external-signal detection)
   "We see it before they say it."
   ============================================================ */

const SIGNAL_SOURCES = [
  { ic:"globe",    name:"Web traffic & engagement", note:"Visit & session trends", live:true },
  { ic:"users",    name:"Hiring & open roles",       note:"Job posts pulled / frozen", live:true },
  { ic:"trend",    name:"Headcount trends",          note:"Net team growth & departures", live:true },
  { ic:"scale",    name:"Funding & cap-table events", note:"Time since last raise", live:true },
  { ic:"bell",     name:"News & press monitoring",   note:"Layoffs, exec exits, filings", live:true },
  { ic:"link",     name:"Domain & infrastructure",   note:"Plan downgrades, cert lapses", live:true },
  { ic:"cpu",      name:"Public code activity",      note:"Commit & release velocity", live:true },
  { ic:"database", name:"App & product signals",     note:"Reviews, status, churn chatter", live:true },
  { ic:"file",     name:"Grant & regulatory filings", note:"IIA reporting cadence", live:true },
  { ic:"target",   name:"Customer & review velocity", note:"Sentiment & volume shifts", live:false }
];

// detected purely from external signals (not self-reported)
const DETECTED = [
  { id:"climor", code:"TX-9012", sector:"Climate / Earth Observation", domain:"agritech",
    confidence:88, lead:"5 mo", status:"new", linked:null,
    signals:[
      { ic:"globe", src:"Web traffic", label:"−41% sessions · 90d", dir:"down" },
      { ic:"users", src:"Hiring", label:"7 open roles pulled", dir:"down" },
      { ic:"scale", src:"Funding", label:"No raise in 21 mo", dir:"flag" },
      { ic:"bell", src:"Press", label:"VP Eng departure reported", dir:"flag" }
    ],
    why:"Sharp traffic decline plus a full hiring freeze and a senior departure — a pattern that typically precedes a quiet wind-down by ~5 months." },
  { id:"galil", code:"TX-6033", sector:"Agritech / Robotics", domain:"agritech",
    confidence:91, lead:"2 mo", status:"engaged", linked:"galil",
    signals:[
      { ic:"file", src:"Grant filing", label:"Wind-down notice filed", dir:"flag" },
      { ic:"trend", src:"Headcount", label:"−18% in 60d", dir:"down" },
      { ic:"cpu", src:"Code activity", label:"Commits −64%", dir:"down" }
    ],
    why:"Already engaged. Detection led the public wind-down notice by ~8 weeks — preservation work started early." },
  { id:"voxen", code:"TX-9027", sector:"Voice AI / Contact Center", domain:"ai",
    confidence:84, lead:"4 mo", status:"new", linked:null,
    signals:[
      { ic:"database", src:"App reviews", label:"Rating 4.6 → 3.8", dir:"down" },
      { ic:"trend", src:"Headcount", label:"−15% in 90d", dir:"down" },
      { ic:"cpu", src:"Code activity", label:"Release cadence stalled", dir:"down" },
      { ic:"globe", src:"Web traffic", label:"−27% · 60d", dir:"down" }
    ],
    why:"Product momentum and team are both softening together — strong, mature tech that may need a home before runway forces a rushed outcome." },
  { id:"arbel", code:"TX-5108", sector:"Cybersecurity / AI", domain:"cyber",
    confidence:79, lead:"3 mo", status:"engaged", linked:"arbel",
    signals:[
      { ic:"scale", src:"Funding", label:"No raise in 17 mo", dir:"flag" },
      { ic:"users", src:"Hiring", label:"2 roles withdrawn", dir:"down" },
      { ic:"bell", src:"Press", label:"Layoff mention (2)", dir:"flag" }
    ],
    why:"Founder already engaged after our outreach. Buyer matching is underway in the MDR space." },
  { id:"prisma", code:"TX-9041", sector:"Foodtech / Fermentation", domain:"agritech",
    confidence:72, lead:"6 mo", status:"drafted", linked:null,
    signals:[
      { ic:"link", src:"Infrastructure", label:"Cloud plan downgraded", dir:"down" },
      { ic:"scale", src:"Funding", label:"No raise in 18 mo", dir:"flag" },
      { ic:"users", src:"Hiring", label:"Hiring frozen", dir:"down" }
    ],
    why:"Early, low-confidence signal — but a 6-month lead time means a gentle note now keeps every option open." },
  { id:"keren", code:"TX-9055", sector:"Fintech / Lending Infra", domain:"fintech",
    confidence:68, lead:"7 mo", status:"new", linked:null,
    signals:[
      { ic:"target", src:"Customer signals", label:"Review velocity −33%", dir:"down" },
      { ic:"globe", src:"Web traffic", label:"−22% · 90d", dir:"down" }
    ],
    why:"Faint but consistent demand softening. Worth watching; not yet worth alarming anyone." }
];

const STATUS_META = {
  new:     ["info",  "Not yet contacted"],
  drafted: ["watch", "Outreach drafted"],
  engaged: ["ok",    "Founder engaged"]
};

function SignalChip({ s }){
  const col = s.dir==="down" ? "var(--risk)" : s.dir==="up" ? "var(--ok)" : "var(--amber)";
  const arrow = s.dir==="down" ? "↓" : s.dir==="up" ? "↑" : "•";
  return (
    <span className="row gap8" style={{padding:"7px 11px", background:"var(--paper-raised)", border:"1px solid var(--line)", borderRadius:9, fontSize:12.5}}>
      <Icon name={s.ic} size={13} style={{color:"var(--sage)", flex:"none"}}/>
      <span style={{color:"var(--ink-2)"}}><b style={{color:"var(--ink)"}}>{s.src}</b> · {s.label}</span>
      <span style={{color:col, fontWeight:700, fontFamily:"var(--mono)"}}>{arrow}</span>
    </span>
  );
}

function DetectedCard({ d, onOutreach, openProfile }){
  const [sc,sl] = STATUS_META[d.status];
  const company = d.linked ? window.TZ.COMPANIES.find(c=>c.id===d.linked) : null;
  return (
    <div className="card" style={{overflow:"hidden"}}>
      <div className="card-pad" style={{padding:20}}>
        <div className="row between mb14" style={{alignItems:"flex-start"}}>
          <div className="row gap12">
            <div className="side-mark" style={{width:42,height:42,background:"var(--paper-sunken)",boxShadow:"none",border:"1px solid var(--line)",flex:"none"}}>
              <Icon name={SECTOR_ICON[d.domain]||SECTOR_ICON.default} size={20} style={{color:"var(--pine)"}}/>
            </div>
            <div className="col" style={{gap:2}}>
              <div className="row gap8"><span className="mono" style={{fontSize:11.5, color:"var(--sage)"}}>{d.code}</span><span className={"badge "+sc}>{sl}</span></div>
              <span style={{fontSize:14.5, fontWeight:600, color:"var(--ink)"}}>{d.sector}</span>
            </div>
          </div>
          <div className="col" style={{alignItems:"flex-end", gap:1}}>
            <span className="serif" style={{fontSize:30, fontWeight:600, lineHeight:1, color: d.confidence>=85?"var(--risk)":d.confidence>=75?"var(--amber)":"var(--sage)"}}>{d.confidence}</span>
            <span className="mono" style={{fontSize:9.5, letterSpacing:".08em", color:"var(--sage-2)"}}>SIGNAL CONFIDENCE</span>
          </div>
        </div>

        <div className="row gap8 wrap mb14">
          {d.signals.map((s,i)=><SignalChip key={i} s={s}/>)}
        </div>

        <div style={{padding:"11px 13px", background:"var(--info-bg)", border:"1px solid #cfdde2", borderRadius:10, marginBottom:14}}>
          <div className="row gap8" style={{alignItems:"flex-start"}}>
            <Icon name="radar" size={15} style={{color:"var(--info)", marginTop:1, flex:"none"}}/>
            <span style={{fontSize:13, color:"var(--ink-2)", lineHeight:1.45}}>{d.why}</span>
          </div>
        </div>

        <div className="row between">
          <span className="row gap6" style={{fontSize:12.5, color:"var(--sage)"}}>
            <Icon name="clock" size={14}/> Detected <b style={{color:"var(--ink)"}}>~{d.lead}</b> ahead of public distress
          </span>
          {d.status==="engaged"
            ? <button className="btn btn-ghost btn-sm" onClick={()=>company&&openProfile(company)}>View preservation profile <Icon name="arrowRight" size={13}/></button>
            : <button className="btn btn-primary btn-sm" onClick={()=>onOutreach(d)}><Icon name="broadcast" size={14}/> {d.status==="drafted"?"Review outreach":"Draft confidential outreach"}</button>}
        </div>
      </div>
    </div>
  );
}

function Signals({ onOutreach, openProfile, go }){
  const [filter,setFilter] = useState("all");
  const list = filter==="all"? DETECTED : DETECTED.filter(d=>d.status===filter);
  const newCount = DETECTED.filter(d=>d.status==="new").length;

  return (
    <div className="fadein">
      <PageHd eyebrow="Proactive detection · external signals"
        title="Signal Radar"
        sub="We surface companies from public signals — traffic, hiring, funding, code, press — often months before they would ever raise a hand. Then we reach out, gently.">
        <span className="chip green"><span className="chip-dot"/> 10 sources live</span>
        <button className="btn btn-ghost btn-sm" onClick={()=>go("agent")}><Icon name="spark" size={14} style={{color:"var(--amber)"}}/> Ask the agent</button>
      </PageHd>

      {/* hero framing band */}
      <div className="card mb24" style={{overflow:"hidden", background:"var(--pine)", color:"#fff", border:"none"}}>
        <div style={{display:"grid", gridTemplateColumns:"1.3fr 1fr"}}>
          <div style={{padding:"28px 32px"}}>
            <div className="row gap10 mb14"><Icon name="broadcast" size={22} style={{color:"var(--amber-2)"}}/><span className="eyebrow" style={{color:"var(--amber-2)"}}>The Techiyat superpower</span></div>
            <h2 className="serif" style={{fontSize:27, color:"#fff", lineHeight:1.14, maxWidth:440}}>We see it before they say it.</h2>
            <p style={{fontSize:14.5, color:"rgba(238,243,239,.78)", lineHeight:1.6, marginTop:12, maxWidth:480}}>
              No founder has to self-report distress to be helped. Techiyat continuously reads public signals across the
              ecosystem and reaches out with a private, no-obligation note — early enough that every option is still open.
            </p>
            <div className="row gap10 wrap" style={{marginTop:18}}>
              {[["radar","Detect","Public signals, continuously"],["broadcast","Reach out","Gentle, consent-based"],["sprout","Preserve","Founder opts in, on their terms"]].map(([ic,t,dsc])=>(
                <div key={t} className="row gap10" style={{padding:"10px 13px", background:"rgba(255,255,255,.06)", border:"1px solid rgba(255,255,255,.12)", borderRadius:11}}>
                  <Icon name={ic} size={17} style={{color:"var(--amber-2)", flex:"none"}}/>
                  <div className="col" style={{gap:0}}><span style={{fontSize:13, fontWeight:600, color:"#fff"}}>{t}</span><span style={{fontSize:11.5, color:"rgba(238,243,239,.6)"}}>{dsc}</span></div>
                </div>
              ))}
            </div>
          </div>
          <div className="col" style={{justifyContent:"center", gap:0, padding:"28px 32px", borderLeft:"1px solid rgba(255,255,255,.1)"}}>
            {[["23","companies surfaced this week"],["~4.2 mo","median lead time vs. self-report"],["0","needed to ask for help first"]].map(([v,l],i)=>(
              <div key={l} style={{padding:"12px 0", borderTop:i?"1px solid rgba(255,255,255,.1)":"none"}}>
                <div className="serif" style={{fontSize:30, fontWeight:600, color:"#fff", lineHeight:1}}>{v}</div>
                <div style={{fontSize:12.5, color:"rgba(238,243,239,.6)", marginTop:3}}>{l}</div>
              </div>
            ))}
          </div>
        </div>
      </div>

      <div className="grid" style={{gridTemplateColumns:"1.55fr 1fr", gap:18, alignItems:"start"}}>
        {/* detected list */}
        <div>
          <div className="row between mb16">
            <div className="row gap8">
              {[["all","All"],["new",`New (${newCount})`],["drafted","Drafted"],["engaged","Engaged"]].map(([k,l])=>(
                <button key={k} className="btn btn-sm" onClick={()=>setFilter(k)}
                  style={{background:filter===k?"var(--pine)":"var(--paper-card)", color:filter===k?"#fff":"var(--ink-2)", border:"1px solid "+(filter===k?"var(--pine)":"var(--line-2)")}}>{l}</button>
              ))}
            </div>
            <span className="muted" style={{fontSize:13}}>{list.length} detected</span>
          </div>
          <div className="col gap16 stagger">
            {list.map(d=><DetectedCard key={d.id} d={d} onOutreach={onOutreach} openProfile={openProfile}/>)}
          </div>
        </div>

        {/* sources monitored */}
        <div style={{position:"sticky", top:78}}>
          <div className="card" style={{overflow:"hidden"}}>
            <div className="card-hd between">
              <div className="row gap10"><Icon name="satellite" size={16} style={{color:"var(--pine)"}}/><h3 className="serif" style={{fontSize:15.5}}>Sources monitored</h3></div>
              <span className="badge ok">10 live</span>
            </div>
            <div>
              {SIGNAL_SOURCES.map((s,i)=>(
                <div key={s.name} className="row gap12" style={{padding:"11px 18px", borderTop:i?"1px solid var(--line)":"none"}}>
                  <div className="side-mark" style={{width:30,height:30,background:"var(--paper-sunken)",boxShadow:"none",border:"1px solid var(--line)",flex:"none"}}>
                    <Icon name={s.ic} size={14} style={{color:"var(--pine)"}}/>
                  </div>
                  <div className="grow col" style={{gap:0}}>
                    <span style={{fontSize:13, fontWeight:600, color:"var(--ink)"}}>{s.name}</span>
                    <span className="muted" style={{fontSize:11.5}}>{s.note}</span>
                  </div>
                  <span className="row gap6" style={{fontSize:11, color: s.live?"var(--ok)":"var(--sage-2)"}}>
                    <span className="chip-dot" style={{width:7,height:7,background: s.live?"var(--ok)":"var(--sage-2)"}}/>{s.live?"Live":"Beta"}
                  </span>
                </div>
              ))}
            </div>
          </div>
          <div className="card card-pad mt18" style={{background:"var(--amber-bg)", border:"1px solid var(--amber-line)"}}>
            <div className="row gap8 mb8"><Icon name="shield" size={16} style={{color:"var(--amber)"}}/><span style={{fontSize:13.5, fontWeight:700, color:"var(--ink)"}}>Detection ≠ disclosure</span></div>
            <p style={{fontSize:12.5, color:"var(--ink-2)", lineHeight:1.5}}>
              Signals come only from public sources. Nothing is listed, scored publicly, or shared. A founder is never
              named until they respond and choose to engage — confidentiality starts the moment they say yes.
            </p>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Signals, DETECTED, SIGNAL_SOURCES });
