/* Settings modal — BRE-style editor for Vue.ai workflow config.
   Replaces raw JSON textareas with sliders, forms, selects, and rule tables. */
const { useState: useStateBRE, useEffect: useEffectBRE, useMemo: useMemoBRE } = React;

// ---------- Static lookups ----------
const PRODUCTS = ["SMFG PL", "SMFG PL2", "ML", "SMFG Auto", "MVI", "AirTicket", "SMFG Flexi", "SMFG Flexi+"];
const TRIGGER_NAMES = ["EMI_CLOSURE", "HIGH_UTILIZATION", "LOW_FOIR", "CREDIT_HUNGRY", "DELINQUENCY", "INACTIVE", "HIGH_BOUNCE"];
const OPERATORS = ["==", "!=", ">", "<", ">=", "<="];
const LEVELS = ["loan", "customer"];
const LOGICS = ["AND", "OR"];
const NULL_STRATEGIES = ["skip", "default_false", "default_true"];
const CATEGORIES = ["Personal Loan", "BNPL"];

const SECTIONS = [
  { key: "_docs",                           label: "Documentation",     desc: "How this works · APIs · data flow", icon: "docs" },
  { key: "product_selection_engine_params", label: "Product Selection", desc: "Weights · Affinities · Top-N" },
  { key: "recommendation_engine_config",    label: "Reco Engine",       desc: "Scoring · Guidance" },
  { key: "eligibility_config",              label: "Eligibility",       desc: "Per-product rules" },
  { key: "ETB_TRIGGER_CONFIG",              label: "ETB Triggers",      desc: "Existing customers" },
  { key: "NTB_TRIGGER_CONFIG",              label: "NTB Triggers",      desc: "New-to-bank" },
];

const EMPTY_CFG = {
  product_selection_engine_params: {},
  eligibility_config: [],
  recommendation_engine_config: {},
  ETB_TRIGGER_CONFIG: [],
  NTB_TRIGGER_CONFIG: [],
};

// ---------- Form primitives ----------
function Field({ label, help, children, inline }) {
  return (
    <div style={{display:"flex", flexDirection: inline?"row":"column", gap: inline?10:4, alignItems: inline?"center":"stretch", marginBottom:10}}>
      <label style={{font:"600 11px/14px var(--font)", color:"var(--label-2)", minWidth: inline?140:undefined}}>{label}</label>
      <div style={{flex:1, display:"flex", flexDirection:"column", gap:2}}>
        {children}
        {help && <div style={{font:"400 11px/14px var(--font)", color:"var(--label-2)"}}>{help}</div>}
      </div>
    </div>
  );
}

function Slider({ value, onChange, min=0, max=1, step=0.05, suffix }) {
  const v = value ?? 0;
  return (
    <div style={{display:"flex", alignItems:"center", gap:10}}>
      <input type="range" className="slider" min={min} max={max} step={step} value={v}
        onChange={e=>onChange(parseFloat(e.target.value))}
        style={{flex:1, "--v": (max>min ? ((v-min)/(max-min))*100 : 0) + "%"}} />
      <input type="number" className="field num" min={min} max={max} step={step} value={v}
        onChange={e=>{ const n=parseFloat(e.target.value); if(!isNaN(n)) onChange(n); }}
        style={{width:64}} />
      {suffix && <span style={{font:"400 11px/14px var(--font)", color:"var(--label-2)", minWidth:24}}>{suffix}</span>}
    </div>
  );
}

function NumInput({ value, onChange, min, max, step=1, placeholder, width=100 }) {
  return (
    <input type="number" value={value ?? ""} min={min} max={max} step={step} placeholder={placeholder}
      onChange={e=>{ const n = e.target.value === "" ? null : parseFloat(e.target.value); onChange(isNaN(n)?null:n); }}
      className="field num" style={{width}} />
  );
}

function TextInput({ value, onChange, placeholder, width="100%" }) {
  return (
    <input type="text" value={value ?? ""} placeholder={placeholder}
      onChange={e=>onChange(e.target.value)}
      className="field" style={{width}} />
  );
}

function Select({ value, onChange, options, placeholder, width="auto" }) {
  return (
    <select value={value ?? ""} onChange={e=>onChange(e.target.value || null)}
      className="field" style={{width, paddingRight:4}}>
      {placeholder && <option value="">{placeholder}</option>}
      {options.map(o => typeof o === "string"
        ? <option key={o} value={o}>{o}</option>
        : <option key={o.value} value={o.value}>{o.label}</option>
      )}
    </select>
  );
}

function Checkbox({ value, onChange, label }) {
  return (
    <label style={{display:"inline-flex", alignItems:"center", gap:6, font:"500 12px/15px var(--font)", cursor:"pointer"}}>
      <input type="checkbox" checked={!!value} onChange={e=>onChange(e.target.checked)}
        style={{accentColor:"var(--accent)", width:16, height:16, margin:0}} />
      {label && <span>{label}</span>}
    </label>
  );
}

function ChipToggle({ value, onClick, active }) {
  return (
    <button type="button" aria-pressed={!!active} onClick={onClick} className={"btn sm " + (active ? "tinted" : "")}>{value}</button>
  );
}

function Fieldset({ title, subtitle, children, actions }) {
  return (
    <div style={{boxShadow:"0 0 0 1px var(--separator)", borderRadius:"var(--r-inner)", padding:"12px 14px", marginBottom:12, background:"var(--window)"}}>
      <div style={{display:"flex", justifyContent:"space-between", alignItems:"flex-start", marginBottom:10}}>
        <div>
          <div style={{font:"700 13px/16px var(--font)", color:"var(--label-1)"}}>{title}</div>
          {subtitle && <div style={{font:"400 11px/14px var(--font)", color:"var(--label-2)", marginTop:2}}>{subtitle}</div>}
        </div>
        {actions}
      </div>
      {children}
    </div>
  );
}

function IconBtn({ onClick, title, children, danger }) {
  return (
    <button type="button" onClick={onClick} title={title} style={{
      border:"none", background:"transparent", cursor:"pointer",
      padding:"4px 6px", borderRadius:"var(--r-2)",
      color: danger ? "var(--neg)" : "var(--ink-3)",
      fontSize: 12, fontWeight:600, lineHeight:1
    }}>{children}</button>
  );
}

// ---------- Section editors ----------

function ProductSelectionEditor({ value, onChange }) {
  const v = value || {};
  const set = (k, nv) => onChange({ ...v, [k]: nv });
  const aff = v.trigger_product_affinity || {};
  const toggleAff = (trigger, product) => {
    const current = aff[trigger] || [];
    const exists = current.includes(product);
    const next = exists ? current.filter(p => p !== product) : [...current, product];
    set("trigger_product_affinity", { ...aff, [trigger]: next });
  };
  const etbSum = (v.etb_weight_trigger ?? 0) + (v.etb_weight_persona ?? 0) + (v.etb_weight_cluster ?? 0);
  const ntbSum = (v.ntb_weight_trigger ?? 0) + (v.ntb_weight_persona ?? 0);

  return (
    <>
      <Fieldset title="ETB Scoring Weights" subtitle={`Sum = ${etbSum.toFixed(2)} (target 1.00)`}>
        <Field label="Trigger"><Slider value={v.etb_weight_trigger} onChange={x=>set("etb_weight_trigger",x)}/></Field>
        <Field label="Persona"><Slider value={v.etb_weight_persona} onChange={x=>set("etb_weight_persona",x)}/></Field>
        <Field label="Cluster"><Slider value={v.etb_weight_cluster} onChange={x=>set("etb_weight_cluster",x)}/></Field>
      </Fieldset>

      <Fieldset title="NTB Scoring Weights" subtitle={`Sum = ${ntbSum.toFixed(2)} (target 1.00)`}>
        <Field label="Trigger"><Slider value={v.ntb_weight_trigger} onChange={x=>set("ntb_weight_trigger",x)}/></Field>
        <Field label="Persona"><Slider value={v.ntb_weight_persona} onChange={x=>set("ntb_weight_persona",x)}/></Field>
      </Fieldset>

      <Fieldset title="Decision Memory" subtitle="How past accept/reject decisions influence re-recommendation">
        <Field label="Accepted boost" help="Multiplier (>1 amplifies)">
          <Slider value={v.accepted_boost} onChange={x=>set("accepted_boost",x)} min={0} max={2} step={0.05}/>
        </Field>
        <Field label="Rejected penalty" help="Multiplier (<1 dampens)">
          <Slider value={v.rejected_penalty} onChange={x=>set("rejected_penalty",x)} min={0} max={1} step={0.05}/>
        </Field>
        <Field label="Not interested penalty">
          <Slider value={v.not_interested_penalty} onChange={x=>set("not_interested_penalty",x)} min={0} max={1} step={0.05}/>
        </Field>
        <Field label="Existing loan suppression" help="Dampens products already taken">
          <Slider value={v.existing_loan_suppression} onChange={x=>set("existing_loan_suppression",x)} min={0} max={1} step={0.05}/>
        </Field>
      </Fieldset>

      <Fieldset title="Trigger → Product Affinity" subtitle="Which products surface when each trigger fires">
        <div style={{overflowX:"auto"}}>
          <table style={{borderCollapse:"collapse", fontSize:11, width:"100%"}}>
            <thead>
              <tr>
                <th style={{textAlign:"left", padding:"4px 8px", fontSize:10, color:"var(--ink-3)"}}>Trigger</th>
                {PRODUCTS.map(p => <th key={p} style={{padding:"4px 6px", fontSize:10, color:"var(--ink-3)", fontFamily:"var(--font-mono)"}}>{p}</th>)}
              </tr>
            </thead>
            <tbody>
              {TRIGGER_NAMES.map(t => (
                <tr key={t} style={{borderTop:"1px solid var(--divider)"}}>
                  <td style={{padding:"6px 8px", fontFamily:"var(--font-mono)", fontSize:10, fontWeight:600}}>{t}</td>
                  {PRODUCTS.map(p => {
                    const on = (aff[t] || []).includes(p);
                    return (
                      <td key={p} style={{padding:"4px 6px", textAlign:"center"}}>
                        <input type="checkbox" checked={on} onChange={()=>toggleAff(t, p)} style={{accentColor:"var(--brand)", cursor:"pointer"}}/>
                      </td>
                    );
                  })}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </Fieldset>

      <Fieldset title="Priority Boost">
        <Field label="Boost products (ordered)" help="Products listed here are pushed up the ranking">
          <div style={{display:"flex", flexWrap:"wrap", gap:6}}>
            {PRODUCTS.map(p => {
              const list = v.product_boost_priority_score || v.boost_products_priority || [];
              const on = list.includes(p);
              return <ChipToggle key={p} value={p} active={on} onClick={()=>{
                const cur = v.product_boost_priority_score || v.boost_products_priority || [];
                const next = on ? cur.filter(x=>x!==p) : [...cur, p];
                set("product_boost_priority_score", next);
              }}/>;
            })}
          </div>
        </Field>
      </Fieldset>

      <Fieldset title="Limits">
        <Field label="Top N recommendations" inline>
          <NumInput value={v.top_n} onChange={x=>set("top_n",x)} min={1} max={50} step={1}/>
        </Field>
        <Field label="CF min support" inline help="Minimum observations for collaborative filtering">
          <NumInput value={v.cf_min_support} onChange={x=>set("cf_min_support",x)} min={0} step={1}/>
        </Field>
      </Fieldset>
    </>
  );
}

function RecoEngineEditor({ value, onChange }) {
  const v = value || {};
  const set = (k, nv) => onChange({ ...v, [k]: nv });
  const setNested = (k1, k2, nv) => set(k1, { ...(v[k1] || {}), [k2]: nv });
  const etbW = v.etb_scoring_weights || {};
  const ntbW = v.ntb_scoring_weights || {};
  const ib = v.income_band_rank || {};
  const g = v.guidance || {};
  const etbSum = Object.values(etbW).reduce((s,x)=>s+(x||0),0);
  const ntbSum = Object.values(ntbW).reduce((s,x)=>s+(x||0),0);

  return (
    <>
      <Fieldset title="ETB Scoring Weights" subtitle={`Sum = ${etbSum.toFixed(2)}`}>
        {["final_score","eligibility_score","credit_score","foir_slack","income_band"].map(k => (
          <Field key={k} label={k.replace(/_/g," ")}>
            <Slider value={etbW[k]} onChange={x=>setNested("etb_scoring_weights", k, x)}/>
          </Field>
        ))}
      </Fieldset>

      <Fieldset title="NTB Scoring Weights" subtitle={`Sum = ${ntbSum.toFixed(2)}`}>
        {["final_score","eligibility_score","credit_score","income_band"].map(k => (
          <Field key={k} label={k.replace(/_/g," ")}>
            <Slider value={ntbW[k]} onChange={x=>setNested("ntb_scoring_weights", k, x)}/>
          </Field>
        ))}
      </Fieldset>

      <Fieldset title="Income Band Rank">
        {["LOW","MEDIUM","HIGH"].map(k => (
          <Field key={k} label={k}>
            <Slider value={ib[k]} onChange={x=>setNested("income_band_rank", k, x)}/>
          </Field>
        ))}
      </Fieldset>

      <Fieldset title="Credit Score Range">
        <Field label="Min" inline><NumInput value={v.credit_score_min} onChange={x=>set("credit_score_min",x)} min={0} max={999} step={10}/></Field>
        <Field label="Max" inline><NumInput value={v.credit_score_max} onChange={x=>set("credit_score_max",x)} min={0} max={999} step={10}/></Field>
      </Fieldset>

      <Fieldset title="Curated Amount Calculation">
        <Field label="Income multiplier" inline help="Curated amount = monthly_income × this">
          <NumInput value={v.amount_income_multiplier} onChange={x=>set("amount_income_multiplier",x)} min={1} max={100} step={1}/>
        </Field>
        <Field label="Round to (₹)" inline>
          <NumInput value={v.amount_round_to} onChange={x=>set("amount_round_to",x)} min={1} step={1000} width={120}/>
        </Field>
      </Fieldset>

      <Fieldset title="Rate / Tenure">
        <Field label="Rate score power"><Slider value={v.rate_score_power} onChange={x=>set("rate_score_power",x)} min={0.1} max={5} step={0.1}/></Field>
        <Field label="Tenure FOIR high threshold"><Slider value={v.tenure_foir_high_threshold} onChange={x=>set("tenure_foir_high_threshold",x)}/></Field>
        <Field label="Tenure FOIR low threshold"><Slider value={v.tenure_foir_low_threshold} onChange={x=>set("tenure_foir_low_threshold",x)}/></Field>
      </Fieldset>

      <Fieldset title="Guidance Thresholds" subtitle="Trigger the system-guidance badges you see on offers">
        <Field label="FOIR very low"><Slider value={g.foir_very_low} onChange={x=>setNested("guidance","foir_very_low",x)}/></Field>
        <Field label="FOIR high"><Slider value={g.foir_high} onChange={x=>setNested("guidance","foir_high",x)}/></Field>
        <Field label="Credit score prime" inline><NumInput value={g.credit_score_prime} onChange={x=>setNested("guidance","credit_score_prime",x)} min={0} max={999} step={10}/></Field>
        <Field label="Credit score subprime" inline><NumInput value={g.credit_score_subprime} onChange={x=>setNested("guidance","credit_score_subprime",x)} min={0} max={999} step={10}/></Field>
      </Fieldset>
    </>
  );
}

function RuleRow({ rule, onChange, onRemove, showWeight }) {
  return (
    <div style={{display:"grid", gridTemplateColumns: showWeight ? "1.4fr 70px 1fr 120px 28px" : "1.4fr 70px 1fr 28px", gap:6, alignItems:"center", marginBottom:6}}>
      <TextInput value={rule.column} onChange={x=>onChange({...rule, column:x})} placeholder="column e.g. foir"/>
      <Select value={rule.operator} onChange={x=>onChange({...rule, operator:x})} options={OPERATORS}/>
      <TextInput value={rule.value} onChange={x=>onChange({...rule, value: /^-?\d+(\.\d+)?$/.test(x) ? parseFloat(x) : x})} placeholder="value"/>
      {showWeight && <Slider value={rule.weight} onChange={x=>onChange({...rule, weight:x})} min={0} max={1} step={0.05}/>}
      <IconBtn onClick={onRemove} title="Remove" danger>✕</IconBtn>
    </div>
  );
}

function SegmentOverrideCard({ so, onChange, onRemove }) {
  const updateCond = (i, nv) => {
    const seg = [...(so.segment || [])];
    if (nv === null) seg.splice(i, 1); else seg[i] = nv;
    onChange({ ...so, segment: seg });
  };
  const updateOv = (i, nv) => {
    const ov = [...(so.overrides || [])];
    if (nv === null) ov.splice(i, 1); else ov[i] = nv;
    onChange({ ...so, overrides: ov });
  };
  return (
    <div style={{borderRadius:"var(--r-tile)", padding:"10px 12px", marginBottom:8, background:"var(--fill-4)"}}>
      <div style={{display:"flex", justifyContent:"space-between", alignItems:"center", marginBottom:8}}>
        <span style={{font:"700 11px/14px var(--font)"}}>Segment override · priority {so.priority ?? "?"}</span>
        <div style={{display:"flex", gap:6, alignItems:"center"}}>
          <label style={{fontSize:10, color:"var(--ink-3)"}}>Priority</label>
          <NumInput value={so.priority} onChange={x=>onChange({...so, priority:x})} min={1} step={1} width={60}/>
          <IconBtn onClick={onRemove} danger>✕</IconBtn>
        </div>
      </div>
      <div style={{fontSize:10, fontWeight:600, color:"var(--ink-3)", marginBottom:4}}>WHEN (segment conditions, ALL must match)</div>
      {(so.segment || []).map((c, i) => (
        <RuleRow key={i} rule={c} onChange={v=>updateCond(i,v)} onRemove={()=>updateCond(i, null)} showWeight={false}/>
      ))}
      <button type="button" onClick={()=>updateCond((so.segment||[]).length, {column:"", operator:"==", value:""})}
        className="btn sm tinted" style={{marginBottom:10}}>+ add condition</button>

      <div style={{fontSize:10, fontWeight:600, color:"var(--ink-3)", marginBottom:4, marginTop:6}}>THEN (overrides)</div>
      {(so.overrides || []).map((o, i) => (
        <div key={i} style={{display:"grid", gridTemplateColumns:"1.4fr 1fr 28px", gap:6, alignItems:"center", marginBottom:6}}>
          <TextInput value={o.column} onChange={x=>updateOv(i, {...o, column:x})} placeholder="column"/>
          <TextInput value={o.value} onChange={x=>updateOv(i, {...o, value: /^-?\d+(\.\d+)?$/.test(x) ? parseFloat(x) : x})} placeholder="value"/>
          <IconBtn onClick={()=>updateOv(i, null)} danger>✕</IconBtn>
        </div>
      ))}
      <button type="button" onClick={()=>updateOv((so.overrides||[]).length, {column:"", value:""})}
        className="btn sm tinted">+ add override</button>
    </div>
  );
}

function ProductCard({ product, onChange, onRemove }) {
  const p = product;
  const set = (k, v) => onChange({ ...p, [k]: v });
  const updateRule = (i, nv) => {
    const rules = [...(p.base_rules || [])];
    if (nv === null) rules.splice(i, 1); else rules[i] = nv;
    set("base_rules", rules);
  };
  const updateSO = (i, nv) => {
    const sos = [...(p.segment_overrides || [])];
    if (nv === null) sos.splice(i, 1); else sos[i] = nv;
    set("segment_overrides", sos);
  };
  return (
    <Fieldset
      title={`${p.product_id || "New product"} · ${p.display_name || ""}`}
      subtitle={p.category}
      actions={<IconBtn onClick={onRemove} title="Remove product" danger>Remove</IconBtn>}>
      <div className="l-stats" style={{display:"grid", gridTemplateColumns:"repeat(3, 1fr)", gap:10, marginBottom:10}}>
        <Field label="Product ID"><Select value={p.product_id} onChange={x=>set("product_id",x)} options={PRODUCTS} placeholder="-- select --"/></Field>
        <Field label="Category"><Select value={p.category} onChange={x=>set("category",x)} options={CATEGORIES}/></Field>
        <Field label="Eligibility cutoff"><Slider value={p.eligibility_cutoff} onChange={x=>set("eligibility_cutoff",x)}/></Field>
      </div>
      <Field label="Display name"><TextInput value={p.display_name} onChange={x=>set("display_name",x)}/></Field>

      <div style={{font:"700 11px/14px var(--font)", color:"var(--label-2)", margin:"14px 0 6px"}}>Base Rules</div>
      <div style={{display:"grid", gridTemplateColumns:"1.4fr 70px 1fr 120px 28px", gap:6, fontSize:10, color:"var(--ink-3)", marginBottom:4}}>
        <div>Column</div><div>Op</div><div>Value</div><div>Weight</div><div/>
      </div>
      {(p.base_rules || []).map((r, i) => (
        <RuleRow key={i} rule={r} onChange={v=>updateRule(i,v)} onRemove={()=>updateRule(i, null)} showWeight={true}/>
      ))}
      <button type="button" onClick={()=>updateRule((p.base_rules||[]).length, {column:"", operator:">=", value:0, weight:0.5})}
        className="btn sm tinted" style={{marginBottom:10}}>+ add rule</button>

      <div style={{font:"700 11px/14px var(--font)", color:"var(--label-2)", margin:"14px 0 6px"}}>Segment Overrides</div>
      {(p.segment_overrides || []).map((so, i) => (
        <SegmentOverrideCard key={i} so={so} onChange={v=>updateSO(i,v)} onRemove={()=>updateSO(i, null)}/>
      ))}
      <button type="button" onClick={()=>updateSO((p.segment_overrides||[]).length, {priority:1, segment:[], overrides:[]})}
        className="btn sm tinted">+ add segment override</button>
    </Fieldset>
  );
}

function EligibilityEditor({ value, onChange }) {
  const arr = Array.isArray(value) ? value : [];
  const update = (i, nv) => {
    const next = [...arr];
    if (nv === null) next.splice(i, 1); else next[i] = nv;
    onChange(next);
  };
  const add = () => onChange([...arr, {
    product_id: "", display_name: "", category: "Personal Loan",
    base_rules: [], segment_overrides: [], eligibility_cutoff: 0.7
  }]);
  return (
    <>
      {arr.map((p, i) => <ProductCard key={i} product={p} onChange={v=>update(i,v)} onRemove={()=>update(i, null)}/>)}
      <button type="button" onClick={add} className="btn lg tinted" style={{width:"100%"}}>+ Add product eligibility</button>
    </>
  );
}

function TriggerCard({ trigger, onChange, onRemove, otherNames }) {
  const t = trigger;
  const set = (k, v) => onChange({ ...t, [k]: v });
  const updateCond = (i, nv) => {
    const cs = [...(t.conditions || [])];
    if (nv === null) cs.splice(i, 1); else cs[i] = nv;
    set("conditions", cs);
  };
  const sb = t.strength_boost || {};
  const setSB = (k, v) => set("strength_boost", { ...sb, [k]: v });
  const supp = t.suppress_if_triggered || [];
  const toggleSupp = (name) => {
    set("suppress_if_triggered", supp.includes(name) ? supp.filter(x=>x!==name) : [...supp, name]);
  };

  return (
    <Fieldset
      title={`${t.trigger_name || "New trigger"} · priority ${t.priority ?? "?"}`}
      subtitle={t.description}
      actions={<IconBtn onClick={onRemove} title="Remove trigger" danger>Remove</IconBtn>}>

      <div className="l-stats" style={{display:"grid", gridTemplateColumns:"repeat(4, 1fr)", gap:10, marginBottom:10}}>
        <Field label="Name"><Select value={t.trigger_name} onChange={x=>set("trigger_name",x)} options={TRIGGER_NAMES} placeholder="-- select --"/></Field>
        <Field label="Level"><Select value={t.level} onChange={x=>set("level",x)} options={LEVELS}/></Field>
        <Field label="Priority"><NumInput value={t.priority} onChange={x=>set("priority",x)} min={1} step={1}/></Field>
        <Field label="Logic"><Select value={t.logic} onChange={x=>set("logic",x)} options={LOGICS}/></Field>
      </div>
      <Field label="Description"><TextInput value={t.description} onChange={x=>set("description",x)} placeholder="Human-readable explanation"/></Field>
      <Field label="Base strength"><Slider value={t.base_strength} onChange={x=>set("base_strength",x)} min={0} max={1} step={0.05}/></Field>
      <Field label="Null strategy"><Select value={t.null_strategy} onChange={x=>set("null_strategy",x)} options={NULL_STRATEGIES}/></Field>

      <div style={{font:"700 11px/14px var(--font)", color:"var(--label-2)", margin:"14px 0 6px"}}>Conditions</div>
      <div style={{display:"grid", gridTemplateColumns:"1.4fr 70px 1fr 28px", gap:6, fontSize:10, color:"var(--ink-3)", marginBottom:4}}>
        <div>Column</div><div>Op</div><div>Value</div><div/>
      </div>
      {(t.conditions || []).map((c, i) => (
        <RuleRow key={i} rule={c} onChange={v=>updateCond(i,v)} onRemove={()=>updateCond(i, null)} showWeight={false}/>
      ))}
      <button type="button" onClick={()=>updateCond((t.conditions||[]).length, {column:"", operator:">=", value:0})}
        className="btn sm tinted" style={{marginBottom:10}}>+ add condition</button>

      <Field label="Suppress if triggered">
        <div style={{display:"flex", flexWrap:"wrap", gap:6}}>
          {otherNames.map(n => <ChipToggle key={n} value={n} active={supp.includes(n)} onClick={()=>toggleSupp(n)}/>)}
        </div>
      </Field>

      <div style={{marginTop:10}}>
        <Checkbox label="Enable strength boost (dynamic based on column value)"
          value={t.enable_strength_boost} onChange={x=>set("enable_strength_boost",x)}/>
      </div>
      {t.enable_strength_boost && (
        <div style={{marginTop:10, paddingLeft:16, borderLeft:"2px solid var(--brand)"}}>
          <div style={{display:"grid", gridTemplateColumns:"1fr 80px 80px", gap:10}}>
            <Field label="Column"><TextInput value={sb.column} onChange={x=>setSB("column",x)}/></Field>
            <Field label="Min value"><NumInput value={sb.min_val} onChange={x=>setSB("min_val",x)} step={0.01}/></Field>
            <Field label="Max value"><NumInput value={sb.max_val} onChange={x=>setSB("max_val",x)} step={0.01}/></Field>
          </div>
          <div style={{display:"grid", gridTemplateColumns:"1fr 1fr 80px", gap:10}}>
            <Field label="Boost min"><NumInput value={(sb.boost_range||[0,0])[0]} onChange={x=>setSB("boost_range",[x, (sb.boost_range||[0,0])[1]])} step={0.05}/></Field>
            <Field label="Boost max"><NumInput value={(sb.boost_range||[0,0])[1]} onChange={x=>setSB("boost_range",[(sb.boost_range||[0,0])[0], x])} step={0.05}/></Field>
            <Field label="Invert"><Checkbox value={sb.invert} onChange={x=>setSB("invert",x)}/></Field>
          </div>
        </div>
      )}
    </Fieldset>
  );
}

function TriggersEditor({ value, onChange }) {
  const arr = Array.isArray(value) ? value : [];
  const update = (i, nv) => {
    const next = [...arr];
    if (nv === null) next.splice(i, 1); else next[i] = nv;
    onChange(next);
  };
  const add = () => onChange([...arr, {
    trigger_name: "", level: "customer", description: "",
    conditions: [], logic: "AND", priority: (arr.length+1),
    base_strength: 0.5, enable_strength_boost: false,
    suppress_if_triggered: [], null_strategy: "skip"
  }]);
  return (
    <>
      {arr.map((t, i) => (
        <TriggerCard key={i} trigger={t}
          otherNames={arr.filter((_,j)=>j!==i).map(x=>x.trigger_name).filter(Boolean)}
          onChange={v=>update(i,v)} onRemove={()=>update(i, null)}/>
      ))}
      <button type="button" onClick={add} className="btn lg tinted" style={{width:"100%"}}>+ Add trigger</button>
    </>
  );
}

// ---------- Documentation panel ----------
function DocsSection({ title, children }) {
  return (
    <div style={{marginBottom:20}}>
      <h3 style={{font:"700 15px/20px var(--font-display)", margin:"0 0 8px", color:"var(--label-1)"}}>{title}</h3>
      <div style={{font:"400 13px/20px var(--font)", color:"var(--label-2)"}}>{children}</div>
    </div>
  );
}

function Code({ children }) {
  return <code style={{fontFamily:"var(--font-mono)", fontSize:11, padding:"1px 5px", background:"var(--fill-2)", borderRadius:"var(--r-mn)", color:"var(--label-1)"}}>{children}</code>;
}

function Pre({ children }) {
  return <pre style={{fontFamily:"var(--font-mono)", fontSize:11, padding:"10px 12px", background:"var(--fill-4)", boxShadow:"0 0 0 1px var(--separator)", borderRadius:"var(--r-inner)", overflowX:"auto", margin:"8px 0", lineHeight:1.5}}>{children}</pre>;
}

function DocsPanel() {
  const rowCell = {padding:"6px 10px", borderBottom:"1px solid var(--divider)", verticalAlign:"top"};
  const headCell = {padding:"7px 10px", textAlign:"left", font:"600 11px/14px var(--font)", color:"var(--label-2)", borderBottom:"1px solid var(--separator)", background:"var(--window)"};
  return (
    <Fieldset title="Overview" subtitle="Customer 360 + Vue.ai Recommendation Engine">
      <DocsSection title="What is this?">
        A Relationship Manager console for a SMFG India Credit, showing 50 customers (40 ETB + 10 NTB)
        with bureau data, loan history, and AI-powered product recommendations. All data comes from{" "}
        <Code>Vue.ai</Code> datasets and the <Code>SMFG Recommendation Engine</Code> workflow.
      </DocsSection>

      <DocsSection title="Architecture">
        <Pre>{`┌──────────────────────────────────────────────────────────────┐
│  Browser (Customer 360 (live).html)                          │
│    React 18 UMD · Babel-standalone in-browser JSX transform  │
│    Loads window.DATA from data-live.js                       │
│    Refresh AI button → POST /api/refresh/{id} → proxy        │
│    Settings → GET/PUT /api/config → proxy                    │
└────────────────────────┬─────────────────────────────────────┘
                         │
┌────────────────────────▼─────────────────────────────────────┐
│  FastAPI proxy (server.py)                                   │
│    Holds VUEAI_API_KEY + VUEAI_ACCOUNT_ID                    │
│    Submits workflow, polls job, fetches node payload         │
│    Reads/writes workflow_config.json for Settings UI         │
└────────────────────────┬─────────────────────────────────────┘
                         │
┌────────────────────────▼─────────────────────────────────────┐
│  Vue.ai Platform (rbac-gcp-prod.vue.ai)                      │
│    Datasets API · Workflow Engine · Jobs API                 │
└──────────────────────────────────────────────────────────────┘`}</Pre>
      </DocsSection>

      <DocsSection title="Vue.ai APIs used">
        <table style={{width:"100%", borderCollapse:"collapse", fontSize:11, marginTop:4}}>
          <thead>
            <tr>
              <th style={headCell}>Method</th>
              <th style={headCell}>Path</th>
              <th style={headCell}>Purpose</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td style={{...rowCell, fontFamily:"var(--font-mono)", color:"var(--pos)"}}>GET</td>
              <td style={{...rowCell, fontFamily:"var(--font-mono)"}}>/api/v1/datasets/&lbrace;id&rbrace;</td>
              <td style={rowCell}>Dataset metadata (schema, fields, GCS path)</td>
            </tr>
            <tr>
              <td style={{...rowCell, fontFamily:"var(--font-mono)", color:"var(--pos)"}}>GET</td>
              <td style={{...rowCell, fontFamily:"var(--font-mono)"}}>/api/v1/datasets/&lbrace;id&rbrace;/export</td>
              <td style={rowCell}>Returns 2-min pre-signed GCS URL for CSV download</td>
            </tr>
            <tr>
              <td style={{...rowCell, fontFamily:"var(--font-mono)", color:"var(--info)"}}>POST</td>
              <td style={{...rowCell, fontFamily:"var(--font-mono)"}}>/api/v1/workflow/async/run</td>
              <td style={rowCell}>Submit SMFG Recommendation Engine run; returns <Code>job_id</Code></td>
            </tr>
            <tr>
              <td style={{...rowCell, fontFamily:"var(--font-mono)", color:"var(--pos)"}}>GET</td>
              <td style={{...rowCell, fontFamily:"var(--font-mono)"}}>/api/v1/jobs/&lbrace;job_id&rbrace;</td>
              <td style={rowCell}>Poll workflow job status (IN_PROGRESS → COMPLETED)</td>
            </tr>
            <tr>
              <td style={{...rowCell, fontFamily:"var(--font-mono)", color:"var(--pos)"}}>GET</td>
              <td style={{...rowCell, fontFamily:"var(--font-mono)"}}>/api/v1/jobs/&lbrace;job_id&rbrace;/node/Recommendation-Gen/payload</td>
              <td style={rowCell}>Fetch 8 ranked offers with guidance + LLM explanation</td>
            </tr>
          </tbody>
        </table>
        <div style={{fontSize:11, color:"var(--ink-3)", marginTop:8}}>
          Auth headers on every call: <Code>x-api-key</Code> + <Code>account-id</Code>.
        </div>
      </DocsSection>

      <DocsSection title="Datasets">
        <table style={{width:"100%", borderCollapse:"collapse", fontSize:11}}>
          <thead>
            <tr>
              <th style={headCell}>Dataset</th>
              <th style={headCell}>Rows</th>
              <th style={headCell}>Powers</th>
            </tr>
          </thead>
          <tbody>
            <tr><td style={rowCell}>SMFG – Customer Master India</td><td style={rowCell}>50</td><td style={rowCell}>Demographics, employment</td></tr>
            <tr><td style={rowCell}>SMFG – Bureau Data</td><td style={rowCell}>150</td><td style={rowCell}>3 bureau scores (CIBIL · EXPERIAN · EQUIFAX) per customer</td></tr>
            <tr><td style={rowCell}>SMFG – Loan Accounts India</td><td style={rowCell}>80</td><td style={rowCell}>Past Loans & Status tab</td></tr>
            <tr><td style={rowCell}>SMFG – Product Data</td><td style={rowCell}>8</td><td style={rowCell}>Product catalog (min/max/default amount · rate · tenure)</td></tr>
            <tr><td style={rowCell}>SMFG – ETB Customer Level Features</td><td style={rowCell}>40</td><td style={rowCell}>FOIR · utilization · bureau aggregates · persona</td></tr>
            <tr><td style={rowCell}>SMFG – NTB Customer Level Features</td><td style={rowCell}>10</td><td style={rowCell}>New-to-bank applicants</td></tr>
            <tr><td style={rowCell}>SMFG – ETB Loan Level Features</td><td style={rowCell}>80</td><td style={rowCell}>Per-loan enrichment (utilization, bounces, LTV)</td></tr>
          </tbody>
        </table>
      </DocsSection>

      <DocsSection title="Data flow per customer">
        <ol style={{paddingLeft:18, margin:0}}>
          <li><strong>Proxy</strong> POSTs workflow run with <Code>customer_id</Code> + current <Code>workflow_config.json</Code>.</li>
          <li><strong>Vue.ai</strong> runs 4 nodes: <Code>Trigger-Identifier</Code> → <Code>Prod-Eligibility</Code> → <Code>Product-Selection</Code> → <Code>Recommendation-Gen</Code> (~30–90 s).</li>
          <li><strong>Proxy</strong> polls <Code>/jobs/&lbrace;id&rbrace;</Code> every 5 s until <Code>COMPLETED</Code>.</li>
          <li><strong>Proxy</strong> fetches the <Code>Recommendation-Gen</Code> node payload — 8 fully denormalized rows (customer profile + ranked offer + <Code>system_guidance</Code> + <Code>llm_explanation</Code>).</li>
          <li><strong>Adapter</strong> renames <Code>offer_score → composite_score</Code>, short-names loan fields, returns JSON.</li>
          <li><strong>UI</strong> replaces <Code>window.DATA.customers[i].ai</Code> in place and re-renders tabs.</li>
        </ol>
      </DocsSection>

      <DocsSection title="Proxy endpoints">
        <table style={{width:"100%", borderCollapse:"collapse", fontSize:11}}>
          <thead><tr><th style={headCell}>Endpoint</th><th style={headCell}>Purpose</th></tr></thead>
          <tbody>
            <tr><td style={{...rowCell, fontFamily:"var(--font-mono)"}}>GET  /api/health</td><td style={rowCell}>Liveness probe</td></tr>
            <tr><td style={{...rowCell, fontFamily:"var(--font-mono)"}}>POST /api/refresh/&lbrace;customer_id&rbrace;</td><td style={rowCell}>Trigger workflow for one customer, return adapted AI recs</td></tr>
            <tr><td style={{...rowCell, fontFamily:"var(--font-mono)"}}>GET  /api/customers/sync</td><td style={rowCell}>Re-fetch all customer/loan/bureau datasets from Vue.ai (no AI run); used by the sidebar Sync button to detect new records</td></tr>
            <tr><td style={{...rowCell, fontFamily:"var(--font-mono)"}}>GET  /api/config</td><td style={rowCell}>Current workflow config + whether defaults backup exists</td></tr>
            <tr><td style={{...rowCell, fontFamily:"var(--font-mono)"}}>PUT  /api/config</td><td style={rowCell}>Overwrite config (validates top-level keys)</td></tr>
            <tr><td style={{...rowCell, fontFamily:"var(--font-mono)"}}>POST /api/config/reset</td><td style={rowCell}>Restore git-committed defaults</td></tr>
          </tbody>
        </table>
      </DocsSection>

      <DocsSection title="What each config section does">
        <table style={{width:"100%", borderCollapse:"collapse", fontSize:11}}>
          <thead><tr><th style={headCell}>Section</th><th style={headCell}>Controls</th></tr></thead>
          <tbody>
            <tr><td style={rowCell}><strong>Product Selection</strong></td><td style={rowCell}>Weights for trigger/persona/cluster scores, decision-memory boosts, trigger-to-product affinity matrix, Top-N.</td></tr>
            <tr><td style={rowCell}><strong>Reco Engine</strong></td><td style={rowCell}>Final scoring weights, income-band ranks, credit-score range, curated-amount formula, rate/tenure powers, guidance thresholds that drive the pill badges on offers.</td></tr>
            <tr><td style={rowCell}><strong>Eligibility</strong></td><td style={rowCell}>Per-product rules (<Code>foir &lt; 0.6</Code>, <Code>selected_score ≥ 650</Code> …) with weights + segment overrides for affluent, subprime, city-tier segments.</td></tr>
            <tr><td style={rowCell}><strong>ETB / NTB Triggers</strong></td><td style={rowCell}>Behavioural triggers (EMI_CLOSURE, HIGH_UTILIZATION, CREDIT_HUNGRY …) with conditions, priority, suppression rules, and optional dynamic strength boost.</td></tr>
          </tbody>
        </table>
      </DocsSection>

      <DocsSection title="Regenerating all 50 customers">
        Settings edits apply to every <strong>future</strong> Refresh AI call. To rebuild <Code>data-live.js</Code> for all 50:
        <Pre>{`cd proxy && python3 precompute.py    # ~20-25 min at concurrency=3`}</Pre>
        Commit the regenerated <Code>data-live.js</Code> to push it to production.
      </DocsSection>

      <DocsSection title="Deployment">
        <table style={{width:"100%", borderCollapse:"collapse", fontSize:11}}>
          <thead><tr><th style={headCell}>Service</th><th style={headCell}>URL</th><th style={headCell}>Type</th></tr></thead>
          <tbody>
            <tr><td style={rowCell}>Static site</td><td style={{...rowCell, fontFamily:"var(--font-mono)", fontSize:10}}>customer-360-bf14.onrender.com</td><td style={rowCell}>Render static</td></tr>
            <tr><td style={rowCell}>Refresh proxy</td><td style={{...rowCell, fontFamily:"var(--font-mono)", fontSize:10}}>customer-360-proxy.onrender.com</td><td style={rowCell}>Render Python · FastAPI</td></tr>
          </tbody>
        </table>
        <div style={{fontSize:11, color:"var(--ink-3)", marginTop:8}}>
          Settings edits persist on the proxy's ephemeral disk — they survive within a container instance but revert to the git-committed defaults on redeploy. For permanent changes, edit <Code>proxy/workflow_config.json</Code> and commit.
        </div>
      </DocsSection>

      <DocsSection title="Local development">
        <Pre>{`# Proxy (port 8001)
cd proxy && python3 -m uvicorn server:app --host 127.0.0.1 --port 8001

# Static (port 8765)
python3 -m http.server 8765
# → open http://localhost:8765/Customer%20360%20(live).html`}</Pre>
        The HTML auto-detects localhost and points the Refresh AI button at <Code>localhost:8001</Code>; in production it uses the deployed proxy URL.
      </DocsSection>
    </Fieldset>
  );
}

// ---------- Modal ----------
function SettingsModal({ open, onClose }) {
  const [cfg, setCfg] = useStateBRE(null);        // last-saved (for "Reload saved")
  const [edit, setEdit] = useStateBRE(null);      // current edits
  const [active, setActive] = useStateBRE("_docs");
  const [status, setStatus] = useStateBRE(null);
  const [loading, setLoading] = useStateBRE(false);

  
  const load = async () => {
    setLoading(true); setStatus(null);
    try {
      const r = await proxyFetch(`/api/config`);
      if (!r.ok) throw new Error(`HTTP ${r.status}`);
      const data = await r.json();
      setCfg(data.config);
      setEdit(JSON.parse(JSON.stringify(data.config)));
    } catch (e) {
      setStatus({ kind: "error", msg: `Load failed: ${e.message}` });
    } finally { setLoading(false); }
  };

  useEffectBRE(() => { if (open) load(); }, [open]);

  if (!open) return null;

  const setSection = (key, newValue) => setEdit(e => ({ ...e, [key]: newValue }));

  const loadPreset = (preset) => {
    if (preset === "template") {
      setEdit(JSON.parse(JSON.stringify(EMPTY_CFG)));
      setStatus({ kind: "info", msg: "Loaded empty template (not yet saved)" });
    } else if (cfg) {
      setEdit(JSON.parse(JSON.stringify(cfg)));
      setStatus({ kind: "info", msg: "Reverted to last saved state" });
    }
  };

  const save = async () => {
    setLoading(true);
    try {
      const r = await proxyFetch(`/api/config`, {
        method: "PUT", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ config: edit }),
      });
      if (!r.ok) throw new Error(`HTTP ${r.status}: ${await r.text()}`);
      setCfg(JSON.parse(JSON.stringify(edit)));
      setStatus({ kind: "success", msg: "Saved. Next refresh uses this config." });
    } catch (e) {
      setStatus({ kind: "error", msg: `Save failed: ${e.message}` });
    } finally { setLoading(false); }
  };

  const reset = async () => {
    if (!confirm("Restore the git-committed defaults? Overwrites current saved config.")) return;
    setLoading(true);
    try {
      const r = await proxyFetch(`/api/config/reset`, { method: "POST" });
      if (!r.ok) throw new Error(`HTTP ${r.status}: ${await r.text()}`);
      const data = await r.json();
      setCfg(data.config);
      setEdit(JSON.parse(JSON.stringify(data.config)));
      setStatus({ kind: "success", msg: "Defaults restored." });
    } catch (e) {
      setStatus({ kind: "error", msg: `Reset failed: ${e.message}` });
    } finally { setLoading(false); }
  };

  const isDirty = cfg && edit && JSON.stringify(cfg) !== JSON.stringify(edit);

  const statusColor = {
    success: { bg: "var(--pos-bg)", fg: "var(--pos)" },
    error:   { bg: "var(--neg-bg)", fg: "var(--neg)" },
    info:    { bg: "var(--info-bg)", fg: "var(--info)" },
  }[status?.kind] || null;

  const renderActive = () => {
    if (active === "_docs") return <DocsPanel/>;
    if (!edit) return null;
    switch (active) {
      case "product_selection_engine_params":
        return <ProductSelectionEditor value={edit.product_selection_engine_params} onChange={v=>setSection(active, v)}/>;
      case "recommendation_engine_config":
        return <RecoEngineEditor value={edit.recommendation_engine_config} onChange={v=>setSection(active, v)}/>;
      case "eligibility_config":
        return <EligibilityEditor value={edit.eligibility_config} onChange={v=>setSection(active, v)}/>;
      case "ETB_TRIGGER_CONFIG":
      case "NTB_TRIGGER_CONFIG":
        return <TriggersEditor value={edit[active]} onChange={v=>setSection(active, v)}/>;
      default: return null;
    }
  };

  return (
    <div style={{
      position:"fixed", inset:0, zIndex:2000,
      background:"color-mix(in srgb, var(--page-ink) 32%, transparent)",
      display:"flex", alignItems:"center", justifyContent:"center",
      padding:24
    }} onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div style={{
        background:"var(--window)", width:"min(1200px, 100%)", height:"min(800px, 92vh)",
        borderRadius:"var(--r-window)",
        boxShadow:"var(--window-shadow)", display:"flex", flexDirection:"column",
        overflow:"hidden"
      }}>
        {/* Header */}
        <div style={{padding:"14px 16px", borderBottom:"1px solid var(--separator)", display:"flex", alignItems:"center", justifyContent:"space-between", gap:12}}>
          <div>
            <div style={{font:"700 17px/22px var(--font-display)"}}>Workflow configuration</div>
            <div style={{font:"400 11px/14px var(--font)", color:"var(--label-2)", marginTop:2}}>
              Vue.ai SMFG Recommendation Engine · changes apply to subsequent Refresh AI calls
              {isDirty && <span style={{color:"var(--warn)", marginLeft:8, fontWeight:700}}>· unsaved changes</span>}
            </div>
          </div>
          <Btn variant="plain" onClick={onClose} icon={<Icon.x size={12}/>}>Close</Btn>
        </div>

        {/* Body */}
        <div style={{display:"flex", flex:1, minHeight:0}}>
          <div style={{
            width:236, flex:"0 0 236px", margin:8, borderRadius:"var(--r-inner)",
            display:"flex", flexDirection:"column", padding:8, overflow:"auto"
          }} className="glass-thick">
            {SECTIONS.map(s => {
              const on = s.key === active;
              const isDocs = s.key === "_docs";
              return (
                <button key={s.key} type="button" className="row" aria-current={on} onClick={()=>setActive(s.key)} style={{
                  marginBottom: isDocs ? 8 : 2,
                }}>
                  <div style={{font:"600 13px/16px var(--font)", display:"flex", alignItems:"center", gap:6}}>
                    {isDocs && (
                      <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{color:"var(--accent)"}}>
                        <path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/>
                        <path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"/>
                      </svg>
                    )}
                    {s.label}
                  </div>
                  <div style={{font:"400 11px/14px var(--font)", color:"var(--label-2)", marginTop:2}}>{s.desc}</div>
                </button>
              );
            })}
          </div>

          <div className="scroll" style={{flex:1, minWidth:0, overflow:"auto", padding:"12px 16px 16px 8px"}}>
            {loading && !edit ? (
              <div style={{display:"flex", alignItems:"center", justifyContent:"center", height:"100%", color:"var(--ink-3)", fontSize:12}}>Loading config…</div>
            ) : renderActive()}
          </div>
        </div>

        {/* Footer */}
        <div style={{
          padding:"10px 16px", borderTop:"1px solid var(--separator)",
          display:"flex", alignItems:"center", justifyContent:"space-between"
        }}>
          <div style={{display:"flex", gap:6}}>
            <Btn size="sm" variant="ghost" onClick={()=>loadPreset("template")}>Load template</Btn>
            <Btn size="sm" variant="ghost" onClick={()=>loadPreset("current")} disabled={!isDirty}>Revert edits</Btn>
            <Btn size="sm" variant="ghost" onClick={reset} disabled={loading}>Reset to defaults</Btn>
          </div>
          <div style={{display:"flex", gap:10, alignItems:"center"}}>
            {status && (
              <div style={{
                font:"600 11px/1 var(--font)", height:20, display:"inline-flex", alignItems:"center",
                padding:"0 8px", borderRadius:"var(--r-pill)",
                background: statusColor.bg, color: statusColor.fg,
                maxWidth:440, overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap"
              }}>{status.msg}</div>
            )}
            <Btn onClick={onClose}>Cancel</Btn>
            <Btn variant="primary" onClick={save} disabled={loading || !isDirty}>
              {loading ? "Saving…" : "Save"}
            </Btn>
          </div>
        </div>
      </div>
    </div>
  );
}

window.SettingsModal = SettingsModal;
