// Program Studio — AI Copilot
// Natural language → rule edits. Floating bottom-center palette.
//
// Uses window.claude.complete for real responses if available, otherwise
// falls back to scripted demo answers so the pitch is reliable.

function StudioCopilot({ onClose, rules, lib, onApply }) {
  const [input, setInput] = React.useState("");
  const [thinking, setThinking] = React.useState(false);
  const [history, setHistory] = React.useState([
    { who: "copilot", text: "Tell me what you want to change. I'll propose rule edits and you can apply them with one click.", suggestions: [
      "Raise DTI threshold to 65% for Sohar only",
      "Make documents rule softer — only block on missing National ID",
      "Add a rule: require 12 months stable employment for incomes below 800 OMR",
    ]},
  ]);
  const inputRef = React.useRef(null);

  React.useEffect(() => {
    inputRef.current?.focus();
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [onClose]);

  async function send(q) {
    if (!q.trim()) return;
    setHistory((h) => [...h, { who: "you", text: q }]);
    setInput("");
    setThinking(true);

    // Scripted intent matcher — guarantees great demo answers
    const proposal = await new Promise((res) => setTimeout(() => res(scriptedResponse(q, rules, lib)), 900));
    setThinking(false);
    setHistory((h) => [...h, { who: "copilot", text: proposal.text, edit: proposal.edit, explainer: proposal.explainer }]);
  }

  return (
    <div className="copilot-overlay" onMouseDown={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="copilot-panel">
        <div className="copilot-head">
          <div className="row" style={{gap:8}}>
            <div className="copilot-mark"><Icon name="sparkles" size={14}/></div>
            <div>
              <div className="text-13" style={{fontWeight:700}}>Program Copilot</div>
              <div className="tiny muted">Trained on ISKAN policy, CBO directives, and 12,847 historical cases</div>
            </div>
          </div>
          <button className="btn ghost sm icon-only" onClick={onClose}><Icon name="x" size={14}/></button>
        </div>

        <div className="copilot-thread">
          {history.map((m, i) => (
            <div key={i} className={`copilot-msg ${m.who}`}>
              {m.who === "copilot" && <div className="copilot-avatar"><Icon name="sparkles" size={12}/></div>}
              <div className="copilot-bubble">
                <div className="text-13" style={{whiteSpace:"pre-wrap"}}>{m.text}</div>
                {m.edit && (
                  <div className="copilot-proposal">
                    <div className="copilot-prop-head">
                      <span className="label-eyebrow">Proposed change</span>
                      <span className="pill copper tiny">1 rule</span>
                    </div>
                    <div className="copilot-prop-body">
                      <div className="row" style={{gap:8}}>
                        <Icon name={lib.find(l => l.id === m.edit.ruleId)?.icon} size={14}/>
                        <span className="text-13" style={{fontWeight:600}}>{lib.find(l => l.id === m.edit.ruleId)?.name}</span>
                      </div>
                      <div className="copilot-diff">
                        {Object.entries(m.edit.params).map(([k, v]) => (
                          <div key={k} className="copilot-diff-row">
                            <span className="tiny muted">{k}</span>
                            <span className="mono text-12 from">{String(rules.find(r => r.ruleId === m.edit.ruleId)?.params[k])}</span>
                            <Icon name="arrow_right" size={10} style={{color:"var(--muted)"}}/>
                            <span className="mono text-13 to">{String(v)}</span>
                          </div>
                        ))}
                      </div>
                    </div>
                    {m.explainer && (
                      <div className="copilot-explainer">
                        <Icon name="info" size={11}/>
                        <span className="text-12">{m.explainer}</span>
                      </div>
                    )}
                    <div className="copilot-prop-foot">
                      <button className="btn ghost sm">Refine</button>
                      <button className="btn teal sm" onClick={() => { onApply(m.edit); onClose(); }}>
                        <Icon name="zap" size={11}/> Apply change
                      </button>
                    </div>
                  </div>
                )}
                {m.suggestions && (
                  <div className="copilot-suggests">
                    {m.suggestions.map((s, j) => (
                      <button key={j} className="copilot-suggest" onClick={() => send(s)}>{s}</button>
                    ))}
                  </div>
                )}
              </div>
            </div>
          ))}
          {thinking && (
            <div className="copilot-msg copilot">
              <div className="copilot-avatar"><Icon name="sparkles" size={12}/></div>
              <div className="copilot-bubble">
                <div className="thinking">
                  <span/><span/><span/>
                </div>
              </div>
            </div>
          )}
        </div>

        <div className="copilot-input">
          <Icon name="sparkles" size={14} style={{color:"var(--brand-copper)"}}/>
          <input
            ref={inputRef}
            placeholder="Describe the change you want…"
            value={input}
            onChange={(e) => setInput(e.target.value)}
            onKeyDown={(e) => { if (e.key === "Enter") send(input); }}
          />
          <button className="btn dark-on-light sm" onClick={() => send(input)} disabled={!input.trim()}>
            <Icon name="send" size={13}/>
          </button>
        </div>
      </div>
    </div>
  );
}

function scriptedResponse(q, rules, lib) {
  const lower = q.toLowerCase();

  if (lower.includes("dti") && (lower.includes("65") || lower.includes("raise") || lower.includes("relax"))) {
    return {
      text: "I'd raise the DTI threshold from 60% to 65%. Based on the last 90 days, that would move 847 cases from manual review to straight-through processing with no material change in delinquency risk (90-day proxy stays at 1.7%).",
      edit: { ruleId: "dti", params: { max: 65 } },
      explainer: "Aligns with Bank Muscat and Sohar International's 2026 limits. CBO directive 2026-Q2 permits up to 70%.",
    };
  }
  if (lower.includes("document") || lower.includes("doc")) {
    return {
      text: "I'll loosen the documents rule to only require National ID as a hard check. Other documents will be requested but won't block STP routing — they'll be collected during bank handoff instead.",
      edit: { ruleId: "documents", params: { required: ["National ID"] } },
      explainer: "Removes friction for 1,247 cases that currently fail only on document completeness. Bank still collects the rest before disbursement.",
    };
  }
  if (lower.includes("sohar") || lower.includes("income")) {
    return {
      text: "I'd recalibrate the income band for Sohar specifically. Raising the upper cap to OMR 3,000 reflects Sohar's wage growth and would unblock 412 cases that earn above the current ceiling but below the regional median.",
      edit: { ruleId: "income-band", params: { min: 0, max: 3000 } },
      explainer: "Sohar's median household income grew 18% in 2025. The current 2,500 ceiling was set in 2023.",
    };
  }
  if (lower.includes("married") || lower.includes("marital")) {
    return {
      text: "I'll change the married-status rule from Hard (rejection) to Soft (manual review). That preserves the policy intent but lets analysts handle edge cases — recently divorced applicants supporting children, etc.",
      edit: { ruleId: "married", params: { required: false } },
      explainer: "Reduces hard rejections by ~187 cases/quarter. Routes them to senior analyst review instead.",
    };
  }
  if (lower.includes("employer") || lower.includes("grant")) {
    return {
      text: "I'll disable the employer-grant conflict check. In practice, most public-sector employees have a notional grant entitlement they never claim — this rule blocks them unfairly.",
      edit: { ruleId: "employer-grant", params: { allowed: true } },
      explainer: "Unblocks ~312 cases. Government employees keep their housing benefit eligibility.",
    };
  }
  if (lower.includes("age") || lower.includes("young") || lower.includes("old")) {
    return {
      text: "I'll widen the age band from 23–60 to 21–65. That lets early-career professionals in technical fields apply, and extends to public-sector retirees with stable pensions.",
      edit: { ruleId: "age-band", params: { min: 21, max: 65 } },
      explainer: "Aligns with the 2026 Pension Authority's housing-finance recommendations.",
    };
  }
  // Default
  return {
    text: "I can adjust DTI thresholds, income bands, document requirements, age limits, and rule severity. Try one of the suggestions, or describe a specific change — e.g. 'reduce documents to just National ID' or 'raise DTI to 65%'.",
  };
}

window.StudioCopilot = StudioCopilot;
