/* ============================================================
   Edge Capital — Screens B: Risk questionnaire, IPS
   ============================================================ */
const { useState: useStateB, useEffect: useEffectB } = React;

/* ===================== RISK QUESTIONNAIRE ===================== */
function profileFor(score) {
  if (score <= 8) return "Conservative";
  if (score <= 16) return "Balanced";
  return "Aggressive";
}

function Risk({ go, state, setState }) {
  const Q = DATA.riskQuestions;
  const [answers, setAnswers] = useStateB(() => state.riskDone ? DATA.neemaAnswers.slice() : DATA.neemaAnswers.slice());
  const [idx, setIdx] = useStateB(0);
  const [showResult, setShowResult] = useStateB(!!state.riskDone);
  const [alloc, setAlloc] = useStateB(() => DATA.modelBalanced.map((m) => ({ ...m })));
  const [editing, setEditing] = useStateB(false);

  const score = answers.reduce((t, a, i) => t + (a != null ? Q[i].opts[a].s : 0), 0);
  const profile = profileFor(score);

  function pick(oi) { const a = answers.slice(); a[idx] = oi; setAnswers(a); }
  function next() { if (idx < Q.length - 1) setIdx(idx + 1); else finish(); }
  function finish() { setShowResult(true); setState((s) => ({ ...s, riskDone: true, profile })); }

  const allocSegs = alloc.map((a) => ({ key: a.key, label: DATA.ac[a.key].label, color: DATA.ac[a.key].color, pct: a.target }));
  const allocTotal = alloc.reduce((t, a) => t + a.target, 0);

  function bump(key, d) {
    setAlloc((prev) => {
      const band = DATA.ipsBands.find((b) => b.key === key);
      const cur = prev.find((p) => p.key === key);
      const nv = cur.target + d;
      if (nv < band.min || nv > band.max) return prev;
      // take/give from deposits (or bonds) to keep 100
      const other = prev.find((p) => p.key === (key === "deposits" ? "bonds" : "deposits"));
      const ob = DATA.ipsBands.find((b) => b.key === other.key);
      const ov = other.target - d;
      if (ov < ob.min || ov > ob.max) return prev;
      return prev.map((p) => p.key === key ? { ...p, target: nv } : p.key === other.key ? { ...p, target: ov } : p);
    });
  }

  if (!showResult) {
    const q = Q[idx];
    return (
      <div className="content-inner fade">
        <div className="page-head">
          <div>
            <div className="onb-eyebrow">Risk profile · Neema Mushi</div>
            <h1>Risk questionnaire</h1>
            <div className="desc">Six short questions. Scoring is rule-based and the same for every client.</div>
          </div>
        </div>

        <div className="card quiz fade">
          <div className="quiz-top">
            <span className="q-count">Question {idx + 1} <span className="muted">of {Q.length}</span></span>
            <div className="q-dots">
              {Q.map((_, i) => <span key={i} className={"qd" + (i < idx ? " past" : i === idx ? " cur" : "")} />)}
            </div>
          </div>
          <div className="q-text">{q.q}</div>
          <div className="opts">
            {q.opts.map((o, oi) => (
              <button key={oi} className={"opt" + (answers[idx] === oi ? " sel" : "")} onClick={() => pick(oi)}>
                <span className="opt-radio" />{o.t}
              </button>
            ))}
          </div>
          <div className="qnav">
            {idx > 0 && <button className="btn btn-ghost" onClick={() => setIdx(idx - 1)}>Back</button>}
            <div style={{ flex: 1 }} />
            <button className="btn btn-primary" disabled={answers[idx] == null} onClick={next}>
              {idx < Q.length - 1 ? <>Next <Icon name="arrowRight" /></> : <>See result <Icon name="arrowRight" /></>}
            </button>
          </div>
        </div>
      </div>
    );
  }

  // ---- result ----
  const pos = (score / 24) * 100;
  return (
    <div className="content-inner fade">
      <div className="page-head">
        <div>
          <div className="onb-eyebrow">Risk profile · Neema Mushi</div>
          <h1>Profile result</h1>
        </div>
        <button className="btn btn-ghost btn-sm" onClick={() => { setShowResult(false); setIdx(0); }}>Review answers</button>
      </div>

      <div className="result-grid">
        <div className="card card-pad">
          <div className="result-score">
            <div className="profile-big">{profile}</div>
            <div className="score-num tnum">{score}<span>/24</span></div>
          </div>
          <div className="score-bar">
            <div className="zone z1">Conservative</div>
            <div className="zone z2">Balanced</div>
            <div className="zone z3">Aggressive</div>
            <div className="score-marker" style={{ left: pos + "%" }}><span className="dotm" /></div>
          </div>
          <p className="result-expl">Comfortable with measured ups and downs in exchange for steady, long-term growth — backed by a long investment horizon.</p>
        </div>

        <div className="card">
          <div className="card-head">
            <h3>Suggested model allocation</h3>
            <button className="btn btn-subtle btn-sm" onClick={() => setEditing((e) => !e)}><Icon name="edit" />{editing ? "Done" : "Adjust allocation"}</button>
          </div>
          <div className="card-pad">
            <AllocBar segments={allocSegs} height={20} />
            {editing && (
              <div className="adjust">
                <div className="adjust-note"><Icon name="info" style={{ width: 15, height: 15 }} /> Adjust within the limits for a Balanced profile.</div>
                {alloc.map((a) => {
                  const band = DATA.ipsBands.find((b) => b.key === a.key);
                  return (
                    <div className="adj-row" key={a.key}>
                      <span className="adj-sw" style={{ background: DATA.ac[a.key].color }} />
                      <span className="adj-lab">{DATA.ac[a.key].label}</span>
                      <span className="adj-band">{band.min}–{band.max}%</span>
                      <div className="stepper-mini">
                        <button onClick={() => bump(a.key, -1)}>−</button>
                        <span className="tnum">{a.target}%</span>
                        <button onClick={() => bump(a.key, +1)}>+</button>
                      </div>
                    </div>
                  );
                })}
                <div className={"adj-total" + (allocTotal === 100 ? "" : " bad")}>Total {allocTotal}%</div>
              </div>
            )}
          </div>
        </div>
      </div>

      <AdvanceBar hint={<><Icon name="info" style={{ width: 15, height: 15 }} /> Next: generate the Investment Policy Statement</>}>
        <button className="btn btn-green btn-lg" onClick={() => { setState((s) => ({ ...s, riskDone: true, profile, allocation: alloc })); go("ips"); }}>
          Generate IPS <Icon name="arrowRight" />
        </button>
      </AdvanceBar>
    </div>
  );
}

/* ===================== IPS DOCUMENT ===================== */
function IPS({ go, state, setState }) {
  const alloc = state.allocation || DATA.modelBalanced;
  const [obj, setObj] = useStateB(
    "Neema Mushi seeks steady, inflation-beating growth of her capital over a horizon of more than seven years, while accepting moderate short-term fluctuations. The portfolio targets a balanced exposure across Tanzanian government securities, listed DSE equities, collective investment schemes and fixed deposits, consistent with a Balanced risk profile."
  );
  const [sig, setSig] = useStateB(state.ipsSigned ? "signed" : "draft"); // draft | sending | signed
  useEffectB(() => {
    if (sig === "sending") {
      const t = setTimeout(() => { setSig("signed"); setState((s) => ({ ...s, ipsSigned: true })); }, 1700);
      return () => clearTimeout(t);
    }
  }, [sig]);

  const bands = DATA.ipsBands.map((b) => {
    const a = (alloc.find((x) => x.key === b.key) || {}).target;
    return { ...b, target: a != null ? a : b.target };
  });

  return (
    <div className="content-inner fade">
      <div className="page-head">
        <div>
          <div className="onb-eyebrow">Investment Policy Statement · Neema Mushi</div>
          <h1>Investment Policy Statement</h1>
        </div>
        {sig !== "signed"
          ? <Chip kind="amber" icon="edit">Draft — review before sending</Chip>
          : <Chip kind="green" icon="check">Signed · v1.0</Chip>}
      </div>

      <div className="ips-doc">
        <div className="ips-sheet">
          <div className="ips-letterhead">
            <img src="assets/edge-logo.png" alt="Edge Capital" />
            <div className="ips-lh-right">
              <div className="ips-lh-title">Investment Policy Statement</div>
              <div className="ips-lh-sub">Version 1.0 · 11 June 2026</div>
            </div>
          </div>

          <div className="ips-client">
            <div><span className="ips-k">Client</span><span className="ips-v">Neema Mushi</span></div>
            <div><span className="ips-k">Mandate</span><span className="ips-v">Advisory (non-discretionary)</span></div>
            <div><span className="ips-k">Risk profile</span><span className="ips-v">Balanced · 14/24</span></div>
            <div><span className="ips-k">Review cycle</span><span className="ips-v">Annual</span></div>
          </div>

          <div className="ips-section">
            <div className="ips-h">1 · Objectives <span className="draft-pill">AI draft — editable</span></div>
            <textarea className="ips-objectives" value={obj} onChange={(e) => setObj(e.target.value)}
              disabled={sig === "signed"} rows={4} />
          </div>

          <div className="ips-section">
            <div className="ips-h">2 · Strategic allocation &amp; bands</div>
            <table className="tbl ips-bands">
              <thead><tr><th>Asset class</th><th className="r">Target</th><th className="r">Minimum</th><th className="r">Maximum</th></tr></thead>
              <tbody>
                {bands.map((b) => (
                  <tr key={b.key}>
                    <td><span className="band-sw" style={{ background: DATA.ac[b.key].color }} />{b.cls}</td>
                    <td className="r tnum">{b.target}%</td>
                    <td className="r tnum muted">{b.min}%</td>
                    <td className="r tnum muted">{b.max}%</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          <div className="ips-section">
            <div className="ips-h">3 · Constraints</div>
            <ul className="ips-constraints">
              <li>Sharia screen — no alcohol-linked equities (excludes Tanzania Breweries).</li>
              <li>No single listed equity to exceed 12% of the portfolio.</li>
              <li>Minimum liquidity buffer of 5% in fixed deposits or money market.</li>
            </ul>
          </div>

          <div className="ips-section ips-sign">
            <div className="ips-h">4 · Client acknowledgement &amp; signature</div>
            <div className="sign-row">
              <div className={"sign-block" + (sig === "signed" ? " done" : "")}>
                {sig === "signed"
                  ? <span className="sign-script">Neema Mushi</span>
                  : <span className="sign-empty">Awaiting client signature</span>}
                <div className="sign-line" />
                <div className="sign-cap">Client signature {sig === "signed" && "· e-signed 11 Jun 2026"}</div>
              </div>
              <div className="sign-block done">
                <span className="sign-script">A. Mwakasege</span>
                <div className="sign-line" />
                <div className="sign-cap">Adviser · Edge Capital</div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <AdvanceBar hint={sig === "signed"
        ? <><Icon name="check" style={{ width: 15, height: 15, color: "var(--green-700)" }} /> Signed — IPS is now the client's reference document</>
        : <><Icon name="pen" style={{ width: 15, height: 15 }} /> Sends a secure e-signature request to the client</>}>
        {sig === "draft" && <button className="btn btn-primary btn-lg" onClick={() => setSig("sending")}><Icon name="send" /> Send for signature</button>}
        {sig === "sending" && <button className="btn btn-primary btn-lg" disabled><Icon name="spinner" /> Awaiting signature…</button>}
        {sig === "signed" && <button className="btn btn-green btn-lg" onClick={() => go("portfolio")}>View portfolio <Icon name="arrowRight" /></button>}
      </AdvanceBar>
    </div>
  );
}

Object.assign(window, { Risk, IPS });
