// Program Studio — Inspector (left rail) + Test Panel (right rail)

function StudioInspector({ rules, selectedRuleIdx, lib, onParamChange, onToggle, onRemove, onAddOpen, programMeta }) {
  if (selectedRuleIdx == null || !rules[selectedRuleIdx]) {
    return (
      <aside className="studio-inspector">
        <div className="card card-pad" style={{position:"sticky", top:0}}>
          <div className="label-eyebrow">Program</div>
          <div className="title" style={{marginTop:6, fontSize:15}}>{programMeta.name}</div>
          <div className="muted text-13" style={{marginTop:2}}>{programMeta.nameAr}</div>
          <div className="hr" style={{margin:"14px 0"}}/>
          <div className="muted text-13">Select a rule in the pipeline to configure it, or add a new rule from the library.</div>
          <button className="btn dark-on-light" style={{width:"100%", marginTop:14}} onClick={onAddOpen}>
            <Icon name="plus" size={13}/> Add a rule
          </button>
          <div className="hr" style={{margin:"14px 0"}}/>
          <div className="label-eyebrow">Program-level settings</div>
          <div style={{display:"flex", flexDirection:"column", gap:10, marginTop:8}}>
            <ProgramSetting label="Reservation lock" value="7 days"/>
            <ProgramSetting label="Max financing (normal)" value="OMR 60,000"/>
            <ProgramSetting label="Max financing (integrated)" value="OMR 80,000"/>
            <ProgramSetting label="Max repayment" value="25 years"/>
            <ProgramSetting label="Partner banks" value="9 banks"/>
          </div>
        </div>
      </aside>
    );
  }

  const rule = rules[selectedRuleIdx];
  const meta = lib.find((r) => r.id === rule.ruleId);

  return (
    <aside className="studio-inspector">
      <div className="card" style={{position:"sticky", top:0, overflow:"hidden"}}>
        <div className="inspector-head" style={{background: window.laneTone(meta?.category)}}>
          <div className="row" style={{justifyContent:"space-between"}}>
            <span className="inspector-cat">{meta?.category}</span>
            <span className="inspector-step">#{selectedRuleIdx + 1}</span>
          </div>
          <div className="row" style={{gap:10, marginTop:8, alignItems:"center"}}>
            <Icon name={meta?.icon} size={20}/>
            <div className="inspector-name">{meta?.name}</div>
          </div>
          <div className="inspector-src">From <strong>{meta?.source}</strong></div>
        </div>

        <div className="card-pad" style={{display:"flex", flexDirection:"column", gap:14}}>
          <div className="row" style={{justifyContent:"space-between"}}>
            <div>
              <div className="tiny muted">Rule severity</div>
              <div className="text-13" style={{fontWeight:600, marginTop:2, textTransform:"capitalize"}}>
                {meta?.severity === "reject" ? "Hard — rejects on fail" :
                 meta?.severity === "manual_review" ? "Soft — routes to review" : "Logic"}
              </div>
            </div>
            <label className="toggle">
              <input type="checkbox" checked={rule.enabled} onChange={onToggle}/>
              <span className="toggle-slider"/>
            </label>
          </div>

          <div className="hr"/>

          <RuleEditor ruleId={rule.ruleId} params={rule.params} onChange={onParamChange}/>

          <div className="hr"/>

          <div>
            <div className="label-eyebrow">Citizen explanation</div>
            <div className="text-13" style={{marginTop:6, padding:"10px 12px", background:"var(--paper-warm)", borderRadius:8}}>
              {explanationText(rule.ruleId, rule.params)}
            </div>
          </div>

          <div className="row" style={{gap:8}}>
            <button className="btn ghost sm" style={{flex:1}}><Icon name="clock" size={12}/> History</button>
            <button className="btn ghost sm" onClick={onRemove}><Icon name="x" size={12}/></button>
          </div>
        </div>
      </div>
    </aside>
  );
}

function ProgramSetting({ label, value }) {
  return (
    <div className="row" style={{justifyContent:"space-between"}}>
      <span className="text-13 muted">{label}</span>
      <span className="text-13" style={{fontWeight:600}}>{value}</span>
    </div>
  );
}

function RuleEditor({ ruleId, params, onChange }) {
  switch (ruleId) {
    case "nationality":
      return (
        <Field label="Nationality must equal">
          <select className="select" value={params.equals} onChange={(e) => onChange({ equals: e.target.value })}>
            <option>Omani</option>
            <option>Any GCC</option>
            <option>Any</option>
          </select>
        </Field>
      );
    case "age-band":
      return (
        <>
          <div className="grid-2" style={{gap:10}}>
            <Field label="Min age">
              <input className="input" type="number" value={params.min} onChange={(e) => onChange({ min: +e.target.value })}/>
            </Field>
            <Field label="Max age">
              <input className="input" type="number" value={params.max} onChange={(e) => onChange({ max: +e.target.value })}/>
            </Field>
          </div>
          <RangeVis min={params.min} max={params.max} absMin={18} absMax={70} unit="years"/>
        </>
      );
    case "married":
      return (
        <Field label="Marital status">
          <ChoiceRow
            options={[{val: true, label: "Married only"}, {val: false, label: "Any"}]}
            value={params.required ?? true}
            onChange={(v) => onChange({ required: v })}
          />
        </Field>
      );
    case "income-band":
      return (
        <>
          <div className="grid-2" style={{gap:10}}>
            <Field label="Min OMR/month">
              <input className="input" type="number" value={params.min} onChange={(e) => onChange({ min: +e.target.value })}/>
            </Field>
            <Field label="Max OMR/month">
              <input className="input" type="number" value={Math.min(params.max, 5000)} onChange={(e) => onChange({ max: +e.target.value })}/>
            </Field>
          </div>
          <ChoiceRow
            options={[{val: 999999, label:"No upper cap"},{val: 2500, label:"2,500"},{val:1000, label:"1,000"}]}
            value={params.max > 99999 ? 999999 : params.max}
            onChange={(v) => onChange({ max: v })}
          />
        </>
      );
    case "dti":
      return (
        <>
          <Field label={`Max DTI: ${params.max}%`}>
            <input type="range" min="10" max="80" step="1" value={params.max} onChange={(e) => onChange({ max: +e.target.value })} className="range"/>
          </Field>
          <DtiVis max={params.max}/>
        </>
      );
    case "existing-property":
    case "active-benefit":
      return (
        <Field label="When match found">
          <ChoiceRow
            options={[{val: false, label: "Block applicant"}, {val: true, label: "Allow"}]}
            value={params.allowed}
            onChange={(v) => onChange({ allowed: v })}
          />
        </Field>
      );
    case "documents": {
      const required = params.required || [];
      return (
        <Field label="Required documents">
          <div style={{display:"flex", flexDirection:"column", gap:6}}>
            {required.map((d, i) => (
              <div key={i} className="doc-pill">
                <Icon name="doc" size={12}/> <span style={{flex:1}}>{d}</span>
                <button className="btn ghost sm icon-only" onClick={() => onChange({ required: required.filter((_, j) => j !== i) })}>
                  <Icon name="x" size={11}/>
                </button>
              </div>
            ))}
            <button className="btn ghost sm" style={{justifyContent:"flex-start"}}>
              <Icon name="plus" size={12}/> Add document
            </button>
          </div>
        </Field>
      );
    }
    case "waiting-list":
      return (
        <Field label="Waiting-list condition">
          <ChoiceRow
            options={[{val: true, label: "Turn must be due"},{val: false, label: "Any position"}]}
            value={params.mustBeDue}
            onChange={(v) => onChange({ mustBeDue: v })}
          />
        </Field>
      );
    default:
      return <div className="muted text-13">No specific parameters for this rule.</div>;
  }
}

function Field({ label, children }) {
  return (
    <div>
      <div className="field-label">{label}</div>
      {children}
    </div>
  );
}

function ChoiceRow({ options, value, onChange }) {
  return (
    <div className="choice-row">
      {options.map((o) => (
        <button key={String(o.val)} className={`choice ${o.val === value ? "active" : ""}`} onClick={() => onChange(o.val)}>
          {o.label}
        </button>
      ))}
    </div>
  );
}

function RangeVis({ min, max, absMin, absMax, unit }) {
  const span = absMax - absMin;
  const left = ((min - absMin) / span) * 100;
  const width = ((max - min) / span) * 100;
  return (
    <div className="range-vis">
      <div className="range-track">
        <div className="range-fill" style={{left: `${left}%`, width: `${width}%`}}/>
      </div>
      <div className="row" style={{justifyContent:"space-between", marginTop:6}}>
        <span className="tiny muted">{absMin} {unit}</span>
        <span className="tiny muted">{absMax} {unit}</span>
      </div>
    </div>
  );
}

function DtiVis({ max }) {
  return (
    <div className="dti-vis">
      <div className="dti-bar">
        <div className="dti-zone safe" style={{width:`${(max/100)*100}%`}}>
          <span>Pass</span>
        </div>
        <div className="dti-zone block" style={{width:`${(1 - max/100)*100}%`}}>
          <span>Review/Block</span>
        </div>
      </div>
      <div className="row" style={{justifyContent:"space-between", marginTop:6}}>
        <span className="tiny muted">0%</span>
        <span className="tiny muted">{max}%</span>
        <span className="tiny muted">100%</span>
      </div>
    </div>
  );
}

function explanationText(ruleId, params) {
  switch (ruleId) {
    case "nationality": return `Civil Registry must confirm the applicant is ${params.equals}.`;
    case "age-band": return `Applicant must be between ${params.min} and ${params.max} years old.`;
    case "married": return `Applicant must be married per Civil Registry records.`;
    case "income-band": return params.max > 99999
      ? `No income cap; any income is accepted.`
      : `Monthly income must be between OMR ${params.min.toLocaleString()} and OMR ${params.max.toLocaleString()}.`;
    case "dti": return `Debt-to-income ratio must be at or below ${params.max}%.`;
    case "existing-property": return params.allowed
      ? `Existing property does not block this application.`
      : `Existing residential property blocks eligibility.`;
    case "active-benefit": return params.allowed
      ? `Active housing benefit is allowed.`
      : `An active housing benefit blocks eligibility.`;
    case "documents": return `Applicant must have these documents on file: ${(params.required || []).join(", ")}.`;
    case "waiting-list": return params.mustBeDue
      ? `Applicant's waiting-list turn must be due.`
      : `Position on waiting list does not gate this step.`;
    default: return `Rule applies as configured.`;
  }
}

window.StudioInspector = StudioInspector;
