/* Tab 1: 360° View — overview grid */
function Tab360({ c, mode }) {
  const isETB = mode === "ETB";

  // Signal roll-up pulled from top AI rec
  const topSignals = (c.ai?.[0]?.system_guidance || []).slice(0,4);

  // Derive relationship tenure from the earliest loan's opened date
  // when the feature dataset doesn't provide customer_since directly.
  const _openings = (c.loans || []).map(l => l.opened).filter(Boolean).sort();
  const _earliest = _openings[0];
  const _derivedMonths = _earliest
    ? Math.max(0, (new Date().getFullYear() - new Date(_earliest).getFullYear()) * 12
                + (new Date().getMonth() - new Date(_earliest).getMonth()))
    : 0;
  const tenureMonths = c.relationship_tenure_months || _derivedMonths;
  const customerSince = c.customer_since || (_earliest ? _earliest.slice(0, 7) : null);

  return (
    <div className="l-split" style={{display:"grid", gridTemplateColumns:"minmax(0,2fr) minmax(0,1.1fr)", gap:12}}>
      {/* LEFT COLUMN */}
      <div style={{display:"flex", flexDirection:"column", gap:12}}>
        {/* Snapshot row */}
        <Card title="Customer Snapshot" tight>
          <div className="l-stats" style={{display:"grid", gridTemplateColumns:"repeat(6, 1fr)", gap:16}}>
            <Stat label="Relationship" value={isETB ? Math.floor(tenureMonths/12)+"y "+(tenureMonths%12)+"m" : "New"} sub={isETB ? (customerSince ? "Since "+customerSince : "—") : (c.source || "—")}/>
            <Stat label="Branch" value={c.branch || "—"} sub={c.region}/>
            <Stat label="Residence" value={c.residence_type} sub={c.residence_category||"—"}/>
            <Stat label="Employment" value={c.employment_status} sub={c.years_at_current_job? c.years_at_current_job+"y tenure" : "—"}/>
            <Stat label="Dependents" value={c.number_of_dependents} sub={c.marital_status}/>
            <Stat label="Education" value={c.education} sub={c.profession_category || "—"}/>
          </div>
        </Card>

        {/* Credit + Financial block */}
        <div className="l-pair" style={{display:"grid", gridTemplateColumns:"minmax(0,1fr) minmax(0,1fr)", gap:12}}>
          <Card title="Credit Score" subtitle={`Bureau — ${c.report_date ? fmtDate(c.report_date) : "—"}`}>
            <div style={{display:"flex", alignItems:"center", gap:16}}>
              <CreditGauge score={c.selected_score} band={c.credit_score_band} />
              <div style={{flex:1, display:"flex", flexDirection:"column", gap:10}}>
                {Object.entries(c.bureau_scores||{}).map(([k,v])=>(
                  <div key={k} style={{display:"flex", flexDirection:"column", gap:3}}>
                    <div style={{display:"flex", justifyContent:"space-between", fontSize:11}}>
                      <span style={{color:"var(--ink-2)"}}>{k}</span>
                      <span className="num" style={{fontWeight:600}}>{v}</span>
                    </div>
                    <Bar value={v-300} max={600} color={v>=750?"var(--pos)":v>=680?"var(--info)":v>=580?"var(--warn)":"var(--neg)"} />
                  </div>
                ))}
                <div style={{marginTop:4, fontSize:11, color:"var(--ink-3)"}}>
                  <span className="num">{c.total_trade_lines}</span> trade lines · <span className="num">{c.total_enquiries_12m}</span> enquiries / 12m
                </div>
              </div>
            </div>
          </Card>

          <Card title="Financial Ratios">
            <div className="l-pair" style={{display:"grid", gridTemplateColumns:"minmax(0,1fr) minmax(0,1fr)", gap:14}}>
              {isETB ? (
                <>
                  <RingChart value={c.foir} max={1} color="var(--ring-1)" label="FOIR" sublabel={c.foir_band+" band"}
                    tone={c.foir_band==="low" ? {severity:"POSITIVE", label:"Headroom"} : c.foir_band==="moderate" ? {severity:"INFO", label:"OK"} : {severity:"WARNING", label:"Stretched"}} />
                  <RingChart value={c.utilization_ratio} max={1} color="var(--ring-2)" label="Credit Utilisation" sublabel={fmtPct(c.utilization_ratio,0)+" of sanctioned"} />
                  <RingChart value={c.overall_payment_ratio} max={1} color="var(--ring-4)" label="Payment Ratio" sublabel="Paid / due lifetime" />
                  <RingChart value={Math.min(1, (c.total_outstanding||0)/(c.total_sanctioned||1))} max={1} color="var(--ring-3)" label="Book Utilisation" sublabel={`${fmtINR(c.total_outstanding,{compact:true})} / ${fmtINR(c.total_sanctioned,{compact:true})}`} />
                </>
              ) : (
                <>
                  {c.foir_estimated != null && (
                  <RingChart value={c.foir_estimated} max={1} color="var(--ring-1)" label="Est. FOIR (post)" sublabel="After requested EMI"
                    tone={c.foir_estimated < 0.3 ? {severity:"POSITIVE", label:"Within policy"} : {severity:"WARNING", label:"Near cap"}} />
                  )}
                  <RingChart value={(c.selected_score-300)/600} max={1} color="var(--ring-2)" label="Bureau Score" sublabel={c.credit_score_band+" band · "+c.selected_score} />
                </>
              )}
            </div>
          </Card>
        </div>

        {/* Loan portfolio summary */}
        {isETB && (
          <Card title="Loan Portfolio" subtitle={`${c.loan_count} active · ${c.loans?.length||0} total`} actions={<Btn size="sm" variant="ghost" icon={<Icon.arrow size={12}/>}>Open Past Loans</Btn>}>
            <div className="l-stats" style={{display:"grid", gridTemplateColumns:"repeat(4, 1fr)", gap:14}}>
              <Stat label="Sanctioned" value={fmtINR(c.total_sanctioned,{compact:true})}/>
              <Stat label="Outstanding" value={fmtINR(c.total_outstanding,{compact:true})} sub={fmtPct((c.total_outstanding||0)/(c.total_sanctioned||1),0)+" of sanctioned"}/>
              <Stat label="Current EMI" value={fmtINR(c.total_emi,{compact:true})} sub={`of ${fmtINR(c.monthly_income,{compact:true})}/mo`}/>
              <Stat label="Bounces / DPD" value={`${c.total_bounces||0} / ${c.max_dpd_bureau||0}`} sub={c.delinquency_flag?"Has delinquency":"Clean"}/>
            </div>
            <div className="hairline" style={{margin:"12px 0 10px"}}/>
            <div style={{display:"flex", flexDirection:"column", gap:6}}>
              {(c.loans||[]).slice(0,3).map(ln=>(
                <div key={ln.id} style={{display:"grid", gridTemplateColumns:"1.6fr 1fr 1fr 0.8fr 0.8fr 0.6fr", gap:8, padding:"6px 0", fontSize:12, alignItems:"center", borderBottom:"1px dashed var(--divider)"}}>
                  <div>
                    <div style={{fontWeight:600}}>{ln.product}</div>
                    <div className="mono" style={{fontSize:10, color:"var(--ink-3)"}}>{ln.id}</div>
                  </div>
                  <div className="num">{fmtINR(ln.sanctioned,{compact:true})}<div style={{fontSize:10, color:"var(--ink-3)"}}>sanctioned</div></div>
                  <div className="num">{fmtINR(ln.outstanding,{compact:true})}<div style={{fontSize:10, color:"var(--ink-3)"}}>outstanding</div></div>
                  <div className="num">{ln.rate}%<div style={{fontSize:10, color:"var(--ink-3)"}}>rate</div></div>
                  <div className="num">{ln.tenure_remaining}/{ln.tenure}<div style={{fontSize:10, color:"var(--ink-3)"}}>months left</div></div>
                  <Pill severity={ln.status==="Active"?"POSITIVE":ln.status==="Closed"?"NEUTRAL":"WARNING"}>{ln.status}</Pill>
                </div>
              ))}
            </div>
          </Card>
        )}

        {!isETB && c.requested_product && (
          <Card title="Application Details">
            <div className="l-stats" style={{display:"grid", gridTemplateColumns:"repeat(4, 1fr)", gap:14}}>
              <Stat label="Product Requested" value={c.requested_product}/>
              <Stat label="Amount" value={fmtINR(c.requested_amount,{compact:true})}/>
              <Stat label="Tenure" value={c.requested_tenure + " months"}/>
              <Stat label="Source" value={c.source}/>
            </div>
            <div className="hairline" style={{margin:"12px 0 10px"}}/>
            <div style={{display:"flex", gap:8, flexWrap:"wrap"}}>
              {c.kyc_status && <Pill severity={c.kyc_status==="COMPLETE"?"POSITIVE":"WARNING"}>{c.kyc_status}</Pill>}
              {c.risk_grade && <Pill severity="INFO">Risk grade {c.risk_grade}</Pill>}
              <Pill severity="NEUTRAL">Applied {fmtDate(c.application_date)}</Pill>
            </div>
          </Card>
        )}
      </div>

      {/* RIGHT COLUMN */}
      <div style={{display:"flex", flexDirection:"column", gap:12}}>
        {/* AI snapshot */}
        <Card title="AI — Top Signals" subtitle="From latest recommendation run" actions={<Pill severity="INFO">Model v3.2</Pill>}>
          <div style={{display:"flex", flexDirection:"column", gap:8}}>
            {topSignals.length === 0 && <div style={{fontSize:12, color:"var(--ink-3)"}}>No recent signals.</div>}
            {topSignals.map((s,i)=>(
              <div key={i} style={{display:"flex", gap:10, alignItems:"flex-start"}}>
                <Pill severity={s.severity}>{s.severity}</Pill>
                <div style={{flex:1, minWidth:0}}>
                  <div style={{fontWeight:600, fontSize:12}}>{s.label}</div>
                  <div style={{fontSize:11, color:"var(--ink-2)", marginTop:2, lineHeight:1.4}}>{s.detail}</div>
                </div>
              </div>
            ))}
          </div>
        </Card>

        {/* Persona */}
        {c.assigned_persona && (
          <Card title="Behavioural Persona" subtitle={`Cluster ${c.behavior_cluster ?? c.ai?.[0]?.cluster ?? "—"} ·${c.ai?.[0]?.signals_fired ?? "—"} signals fired`}>
            <PersonaTag name={c.assigned_persona} cluster={c.behavior_cluster ?? c.ai?.[0]?.cluster}/>
            <div className="hairline" style={{margin:"10px 0"}}/>
            <div style={{display:"flex", justifyContent:"space-between", fontSize:11, marginBottom:6}}>
              <span style={{color:"var(--ink-2)"}}>Persona similarity</span>
              <span className="num" style={{fontWeight:600}}>{fmtPct(c.ai?.[0]?.persona_cf_score||0,0)}</span>
            </div>
            <Bar value={c.ai?.[0]?.persona_cf_score||0} max={1} color="var(--ring-2)"/>
            <div style={{display:"flex", justifyContent:"space-between", fontSize:11, margin:"10px 0 6px"}}>
              <span style={{color:"var(--ink-2)"}}>Cluster similarity</span>
              <span className="num" style={{fontWeight:600}}>{fmtPct(c.ai?.[0]?.cluster_cf_score||0,0)}</span>
            </div>
            <Bar value={c.ai?.[0]?.cluster_cf_score||0} max={1} color="var(--ring-3)"/>
          </Card>
        )}

        {/* Recent activity */}
        <Card title="Recent Activity" actions={<Btn size="sm" variant="ghost">All</Btn>}>
          <div style={{display:"flex", flexDirection:"column", gap:0}}>
            {(c.activity || []).slice(0,6).map((a,i)=>(
              <div key={i} style={{display:"flex", gap:10, padding:"7px 0", borderBottom: i<(c.activity.length-1)?"1px dashed var(--divider)":"none"}}>
                <div style={{width:6, height:6, borderRadius:"50%", background:"var(--brand)", marginTop:6, flexShrink:0}}/>
                <div style={{flex:1}}>
                  <div style={{display:"flex", justifyContent:"space-between", fontSize:11.5}}>
                    <span style={{fontWeight:600}}>{a.type}</span>
                    <span className="mono" style={{color:"var(--ink-3)", fontSize:10}}>{fmtDate(a.date)}</span>
                  </div>
                  <div style={{fontSize:11, color:"var(--ink-2)", marginTop:1}}>{a.detail}</div>
                </div>
              </div>
            ))}
            {!c.activity && <div style={{fontSize:12, color:"var(--ink-3)"}}>No activity yet.</div>}
          </div>
        </Card>
      </div>
    </div>
  );
}

window.Tab360 = Tab360;
