/* Shell: left sidebar (queue) + top customer header + tab bar. */
const { useState: useStateS } = React;

function Sidebar({ mode, setMode, customers, ntb, selectedId, onSelect, query, setQuery, openSettings, onSynced }) {
  const list = mode === "ETB" ? customers : ntb;
  const filtered = list.filter(c => {
    const q = query.toLowerCase().trim();
    if (!q) return true;
    return (c.full_name||"").toLowerCase().includes(q) ||
           (c.customer_id||c.applicant_id||"").toLowerCase().includes(q) ||
           (c.city||"").toLowerCase().includes(q);
  });

  const [syncing, setSyncing] = useStateS(false);
  const [syncMsg, setSyncMsg] = useStateS(null);

  const handleSync = async () => {
    if (syncing) return;
    setSyncing(true);
    setSyncMsg(null);
    try {
      const r = await proxyFetch(`/api/customers/sync`);
      if (!r.ok) throw new Error(`HTTP ${r.status}: ${await r.text()}`);
      const data = await r.json();

      // Merge: keep existing AI recs for known customer_ids, add new ones with ai=[]
      const idOf = (x) => x.customer_id || x.applicant_id;
      const mergeList = (current, fresh) => {
        const curMap = new Map((current || []).map(c => [idOf(c), c]));
        let added = 0, updated = 0;
        const next = fresh.map(f => {
          const cur = curMap.get(idOf(f));
          if (!cur) { added++; return f; }
          updated++;
          return { ...f, ai: cur.ai || [] };
        });
        return { next, added, updated };
      };

      const etb = mergeList(window.DATA.customers, data.customers);
      const ntbR = mergeList(window.DATA.ntb, data.ntb);
      window.DATA.customers = etb.next;
      window.DATA.ntb = ntbR.next;
      window.DATA.products = data.products;

      const totalAdded = etb.added + ntbR.added;
      setSyncMsg(totalAdded
        ? { kind: "success", txt: `+${totalAdded} new · ${etb.updated + ntbR.updated} updated` }
        : { kind: "info", txt: `No new · ${etb.updated + ntbR.updated} refreshed` });
      if (onSynced) onSynced();
    } catch (e) {
      setSyncMsg({ kind: "error", txt: e.message.slice(0, 60) });
    } finally {
      setSyncing(false);
      setTimeout(() => setSyncMsg(null), 5000);
    }
  };

  const syncTone = syncMsg && (syncMsg.kind === "success" ? "pos" : syncMsg.kind === "error" ? "neg" : "info");

  return (
    <aside className="glass-thick app-side" style={{
      margin: 8,
      borderRadius: "var(--r-inner)",
      display:"flex", flexDirection:"column", minHeight:0
    }}>
      {/* Brand */}
      <div style={{padding:"14px 14px 10px", display:"flex", alignItems:"center", gap:10}}>
        <img src="assets/m2p-logo.svg" alt="M2P" width="30" height="30" className="sq" style={{display:"block", flex:"none"}}/>
        <div style={{minWidth:0}}>
          <div style={{font:"700 15px/18px var(--font-display)", color:"var(--label-1)"}}>Customer 360°</div>
          <div style={{font:"400 11px/14px var(--font)", color:"var(--label-2)"}}>SMFG India Credit · RM Console</div>
        </div>
      </div>

      {/* Flow toggle */}
      <div style={{padding:"2px 10px 8px"}}>
        <div className="seg full" role="group" aria-label="Customer flow">
          {["ETB","NTB"].map(m=>(
            <button key={m} type="button" aria-pressed={mode===m} onClick={()=>setMode(m)}>
              {m} {m==="ETB" ? "· Existing" : "· New-to-Bank"}
            </button>
          ))}
        </div>
      </div>

      {/* Search */}
      <div style={{padding:"0 10px 8px"}}>
        <label className="search">
          <Icon.search size={14}/>
          <input value={query} onChange={e=>setQuery(e.target.value)} aria-label="Search customers"
            placeholder={mode==="ETB"?"Search customer, ID, city…":"Search applicant, ID…"} />
        </label>
      </div>

      {/* Meta row */}
      <div style={{padding:"6px 12px 4px 16px", display:"flex", justifyContent:"space-between", alignItems:"center"}}>
        <div className="eyebrow">{mode==="ETB"?"My Book":"Application Queue"}</div>
        <div style={{display:"flex", alignItems:"center", gap:8}}>
          <Btn size="sm" variant="plain" onClick={handleSync} disabled={syncing} title="Check for new customer records"
            icon={<span style={{display:"inline-block", animation: syncing ? "c3spin 0.9s linear infinite" : "none"}}>↓</span>}>
            {syncing ? "Syncing…" : "Sync"}
          </Btn>
          <span className="badge">{filtered.length} / {list.length}</span>
        </div>
      </div>
      {syncMsg && (
        <div style={{padding:"0 12px 8px"}}>
          <span className={`pill pill--${syncTone}`}>{syncMsg.txt}</span>
        </div>
      )}

      {/* List */}
      <div className="scroll" style={{overflowY:"auto", flex:1, padding:"2px 8px 12px"}}>
        {filtered.map(c => {
          const id = c.customer_id || c.applicant_id;
          const isSel = id === selectedId;
          return (
            <button key={id} type="button" className="row" aria-current={isSel} onClick={()=>onSelect(id)}>
              <div style={{display:"flex", justifyContent:"space-between", alignItems:"baseline", marginBottom:2, gap:8}}>
                <span style={{font:"600 13px/16px var(--font)", whiteSpace:"nowrap", overflow:"hidden", textOverflow:"ellipsis"}}>{c.full_name}</span>
                <span className="num" style={{font:"400 10px/13px var(--font)", color:"var(--label-2)", flex:"none"}}>{id}</span>
              </div>
              <div style={{display:"flex", justifyContent:"space-between", alignItems:"center", font:"400 11px/14px var(--font)", color:"var(--label-2)"}}>
                <span>{c.city} · {c.age}y · {c.gender}</span>
                {mode==="ETB"
                  ? <span className="num" style={{fontWeight:600, color:"var(--label-1)"}}>{c.selected_score}</span>
                  : c.kyc_status
                    ? <Pill severity={c.kyc_status==="COMPLETE"?"POSITIVE":"WARNING"}>{c.kyc_status==="COMPLETE"?"KYC OK":"KYC Pending"}</Pill>
                    : <span className="num" style={{fontWeight:600, color:"var(--label-1)"}}>{c.selected_score}</span>
                }
              </div>
              {mode==="ETB" && (
                <div style={{marginTop:6, display:"flex", gap:4, flexWrap:"wrap"}}>
                  {c.credit_hungry_flag===1 && <Pill severity="ACTION">Credit-hungry</Pill>}
                  {c.inactive_flag===1 && <Pill severity="WARNING">Inactive</Pill>}
                  {c.affluence_indicator===1 && <Pill severity="POSITIVE">Affluent</Pill>}
                  {!c.credit_hungry_flag && !c.inactive_flag && !c.affluence_indicator && <Pill severity="NEUTRAL">{c.credit_score_band}</Pill>}
                </div>
              )}
              {mode==="NTB" && c.requested_product && (
                <div style={{marginTop:6, display:"flex", gap:4, font:"400 11px/14px var(--font)", color:"var(--label-2)"}}>
                  <span>{c.requested_product}</span>
                  <span>·</span>
                  <span className="num">{fmtINR(c.requested_amount, {compact:true})}</span>
                </div>
              )}
            </button>
          );
        })}
      </div>

      {/* Footer RM */}
      <div style={{margin:"0 10px", padding:"10px 4px 12px", borderTop:"1px solid var(--separator)", display:"flex", alignItems:"center", gap:8}}>
        <div style={{width:24, height:24, borderRadius:"50%", background:"linear-gradient(135deg,var(--orange),var(--pink))", color:"#fff", display:"grid", placeItems:"center", font:"700 10px/1 var(--font)"}}>DB</div>
        <div style={{flex:1, minWidth:0}}>
          <div style={{font:"600 12px/15px var(--font)"}}>Devanand Bhatia</div>
          <div style={{font:"400 11px/14px var(--font)", color:"var(--label-2)"}}>Relationship Manager · Delhi</div>
        </div>
        <Btn size="sm" variant="plain" onClick={openSettings} title="Workflow settings" style={{width:24, padding:0, height:24, color:"var(--label-2)"}}
          icon={<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>}/>
        <span style={{display:"inline-flex", color:"var(--label-2)"}}><Icon.bell size={14}/></span>
      </div>
    </aside>
  );
}

function CustomerHeader({ customer, mode, theme, toggleTheme, onRefreshed }) {
  const initials = (customer.full_name||"").split(" ").map(s=>s[0]).slice(0,2).join("");
  const [refreshing, setRefreshing] = useStateS(false);
  const [refreshMsg, setRefreshMsg] = useStateS(null);

  const handleRefresh = async () => {
    const id = customer.customer_id || customer.applicant_id;
    if (!id || refreshing) return;
    setRefreshing(true);
    setRefreshMsg(null);
    try {
      const res = await proxyFetch(`/api/refresh/${id}`, { method: "POST" });
      if (!res.ok) throw new Error(`HTTP ${res.status}: ${await res.text()}`);
      const data = await res.json();
      // Mutate window.DATA in place for this customer
      const list = mode === "ETB" ? window.DATA.customers : window.DATA.ntb;
      const idx = list.findIndex(x => (x.customer_id||x.applicant_id) === id);
      if (idx >= 0) {
        list[idx] = { ...list[idx], ai: data.ai };
      }
      setRefreshMsg(`Updated · ${data.count} recs · ${data.elapsed_s}s`);
      if (onRefreshed) onRefreshed();
    } catch (e) {
      setRefreshMsg(`Error: ${e.message.slice(0, 80)}`);
    } finally {
      setRefreshing(false);
      setTimeout(() => setRefreshMsg(null), 4000);
    }
  };

  const actions = (
    <div style={{display:"flex", gap:8, alignItems:"center", flex:"none"}}>
      <div className="glass" style={{display:"inline-flex", borderRadius:"var(--r-pill)", padding:"0 2px"}}>
        <button type="button" className="gbtn" onClick={handleRefresh} disabled={refreshing} title="Re-run the recommendation engine for this customer">
          <span style={{display:"inline-block", animation: refreshing ? "c3spin 0.9s linear infinite" : "none"}}>↻</span>
          {refreshing ? "Refreshing…" : "Refresh AI"}
        </button>
        <span style={{width:1, height:18, alignSelf:"center", background:"var(--separator)"}}/>
        <button type="button" className="gbtn" onClick={toggleTheme} title={theme==="dark"?"Switch to light":"Switch to dark"} aria-label="Toggle theme" style={{padding:0, width:36}}>
          {theme==="dark" ? <Icon.sun size={16}/> : <Icon.moon size={16}/>}
        </button>
      </div>
      <button type="button" className="gbtn primary"><Icon.plus size={14}/>New offer</button>
    </div>
  );

  const statusBanner = refreshMsg ? (
    <div style={{
      position:"absolute", top:"100%", right:18, marginTop:4, zIndex:10,
      maxWidth:320, padding:"10px 14px", borderRadius:18,
      font:"400 13px/16px var(--font)", color:"var(--label-1)"
    }} className="glass" role="status">
      <b style={{display:"block", font:"700 13px/16px var(--font)", color: refreshMsg.startsWith("Error") ? "var(--red-ink)" : "var(--green-ink)"}}>
        {refreshMsg.startsWith("Error") ? "Refresh failed" : "AI refreshed"}
      </b>
      {refreshMsg.replace(/^Error: /, "")}
    </div>
  ) : null;

  return (
    <header style={{
      background:"var(--window)",
      padding:"14px 16px 0 8px",
      position:"relative"
    }}>
      {statusBanner}
      <div style={{display:"flex", alignItems:"flex-start", justifyContent:"space-between", gap:16}}>
        {/* Identity */}
        <div style={{display:"flex", alignItems:"center", gap:14, minWidth:0, flex:"1 1 auto"}}>
          <div className="sq" style={{
            width:44, height:44, borderRadius:"var(--r-tile)", background:"var(--accent-tint)", color:"var(--accent)",
            display:"inline-flex", alignItems:"center", justifyContent:"center", flex:"none",
            font:"700 15px/1 var(--font-display)", letterSpacing:"-0.02em"
          }}>{initials}</div>
          <div style={{minWidth:0}}>
            <div style={{display:"flex", alignItems:"baseline", gap:10, flexWrap:"wrap"}}>
              <h1 style={{margin:0, font:"700 22px/26px var(--font-display)", letterSpacing:"-0.01em"}}>{customer.full_name}</h1>
              <span className="num" style={{fontSize:11, color:"var(--label-2)"}}>{customer.customer_id || customer.applicant_id}</span>
              <Pill severity={mode==="ETB"?"POSITIVE":"INFO"} size="lg">{mode==="ETB"?"ETB · Existing":"NTB · New-to-Bank"}</Pill>
              {customer.assigned_persona && <Pill severity="NEUTRAL" size="lg">{customer.assigned_persona}</Pill>}
            </div>
            <div style={{display:"flex", gap:14, marginTop:6, font:"400 12px/15px var(--font)", color:"var(--label-2)", flexWrap:"wrap"}}>
              <span>{customer.age} · {customer.gender==="F"?"Female":"Male"} · {customer.marital_status}</span>
              <span>{customer.city}, {customer.region}</span>
              <span>PAN · <span className="mono" style={{fontSize:11}}>{customer.pan || customer.nic}</span></span>
              <span>{customer.phone}</span>
              {mode==="ETB" && customer.customer_since && <span>Customer since {customer.customer_since}</span>}
              {mode==="NTB" && <span>Applied {fmtDate(customer.application_date)}</span>}
            </div>
          </div>
        </div>

        {actions}
      </div>

      {/* KPI strip */}
      <div className="hdr-stats" style={{marginTop:12}}>
            {mode==="ETB" ? (
              <>
                <HeaderStat label="Bureau (best)" value={customer.selected_score} sub={customer.credit_score_band+" band"} />
                <HeaderStat label="Monthly Income" value={fmtINR(customer.monthly_income, {compact:true})} sub={customer.income_band+" band"} />
                <HeaderStat label="Outstanding" value={fmtINR(customer.total_outstanding, {compact:true})} sub={`${customer.loan_count} active loan(s)`} />
                <HeaderStat label="FOIR" value={fmtPct(customer.foir,1)} sub={customer.foir_band+" band"} />
              </>
            ) : (
              <>
                <HeaderStat label="Bureau (best)" value={customer.selected_score} sub={customer.credit_score_band+" band"} />
                <HeaderStat label="Monthly Income" value={fmtINR(customer.monthly_income, {compact:true})} sub={customer.income_band+" band"} />
                {customer.requested_product
                  ? <HeaderStat label="Requested" value={fmtINR(customer.requested_amount, {compact:true})} sub={customer.requested_product} />
                  : <HeaderStat label="Top Offer" value={customer.ai?.[0]?.product || "—"} sub={customer.ai?.[0] ? fmtINR(customer.ai[0].curated_amount, {compact:true}) : "No AI run yet"} />}
                {customer.risk_grade
                  ? <HeaderStat label="Risk Grade" value={customer.risk_grade} sub={"FOIR ~ "+fmtPct(customer.foir_estimated,0)} />
                  : <HeaderStat label="Enquiries 12m" value={customer.total_enquiries_12m ?? "—"} sub={customer.subprime_flag ? "Subprime" : (customer.credit_score_band||"—")+" band"} />}
              </>
            )}
      </div>
    </header>
  );
}

function HeaderStat(props) {
  return <div style={{padding:"8px 12px", borderRadius:"var(--r-tile)", background:"var(--fill-4)", minWidth:0}}><Stat {...props}/></div>;
}

function TabBar({ tabs, active, onChange }) {
  return (
    <div style={{display:"flex", alignItems:"center", gap:12, padding:"14px 16px 10px 8px", background:"var(--window)"}}>
      <div className="tabbar-scroll">
      <div className="seg lg" role="tablist" aria-label="Customer sections">
        {tabs.map(t => {
          const on = t.id === active;
          return (
            <button key={t.id} type="button" role="tab" aria-selected={on} aria-pressed={on} onClick={()=>onChange(t.id)}
              style={{padding:"0 14px", fontWeight: on ? 600 : 500}}>
              <span className="t-long">{t.label}</span><span className="t-short">{t.short || t.label}</span>
              {t.count != null && <span className={"badge" + (on ? " on" : "")}>{t.count}</span>}
            </button>
          );
        })}
      </div>
      </div>
      <span className="pill pill--pos sync-pill" style={{flex:"none"}}>Synced just now</span>
    </div>
  );
}

Object.assign(window, { Sidebar, CustomerHeader, TabBar });
