/* global React, Icon, fmtUSD, fmtUSDc, fmtPct, fmtMonth, SliderRow */
const { useState, useMemo, useRef, useEffect } = React;

/* ============================================================
   Live-dashboard Mortgage Calculator (Direction C)
   - Slider + numeric input pair on every row
   - Hero result with donut
   - "Explain my result" AI panel
   - Methodology drawer + Save / Share / Embed
   ============================================================ */

/* ---------- math ---------- */
function calcMortgage({ price, downPct, ratePct, termYears, taxYr, hoaMo, insYr, pmiEnabled, pmiRate }) {
  const principal = Math.max(0, price - price * (downPct / 100));
  const r = ratePct / 100 / 12;
  const n = termYears * 12;
  const piMonthly = r === 0
    ? principal / n
    : (principal * r * Math.pow(1 + r, n)) / (Math.pow(1 + r, n) - 1);
  const taxMo = (taxYr || 0) / 12;
  const insMo = (insYr || 0) / 12;
  const pmiMo = pmiEnabled ? (principal * (pmiRate || 0) / 100) / 12 : 0;
  const totalMo = piMonthly + taxMo + insMo + (hoaMo || 0) + pmiMo;
  const totalInterest = piMonthly * n - principal;
  const totalPaid = piMonthly * n;
  const payoff = new Date();
  payoff.setMonth(payoff.getMonth() + n);
  return {
    principal, piMonthly, taxMo, insMo, hoaMo: hoaMo || 0, pmiMo, totalMo,
    totalInterest, totalPaid, payoff, n,
  };
}

/* ---------- donut ---------- */
const Donut = ({ values, size = 140, stroke = 18 }) => {
  const total = values.reduce((s, v) => s + v.value, 0) || 1;
  const r = (size - stroke) / 2;
  const c = 2 * Math.PI * r;
  let offset = 0;
  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} aria-hidden="true">
      <circle cx={size / 2} cy={size / 2} r={r} fill="none"
        stroke="var(--surface-2)" strokeWidth={stroke} />
      {values.map((v, i) => {
        const len = (v.value / total) * c;
        const dash = `${len} ${c - len}`;
        const seg = (
          <circle key={i}
            cx={size / 2} cy={size / 2} r={r} fill="none"
            stroke={v.color} strokeWidth={stroke}
            strokeDasharray={dash}
            strokeDashoffset={-offset}
            strokeLinecap="butt"
            transform={`rotate(-90 ${size / 2} ${size / 2})`}
            style={{ transition: "stroke-dasharray 220ms var(--ease), stroke-dashoffset 220ms var(--ease)" }}
          />
        );
        offset += len;
        return seg;
      })}
    </svg>
  );
};

/* ---------- AI Explain panel ---------- */
const ExplainPanel = ({ result, inputs }) => {
  const yearOneInterest = result.principal * (inputs.ratePct / 100);
  const interestRatio = (result.totalInterest / result.principal) * 100;
  const extra200 = useMemo(() => {
    // crude "what if you paid +$200/mo extra"
    const r = inputs.ratePct / 100 / 12;
    const extra = 200;
    let bal = result.principal;
    let months = 0;
    let interest = 0;
    while (bal > 0 && months < 600) {
      const int = bal * r;
      const pay = result.piMonthly + extra - int;
      bal -= pay; interest += int; months++;
      if (bal < 0) bal = 0;
    }
    return {
      interestSaved: result.totalInterest - interest,
      monthsSaved: result.n - months,
    };
  }, [result, inputs.ratePct]);

  const pulls = [
    {
      icon: "info",
      title: "Most of year one is interest",
      body: <>In your first 12 months, ~<b>{fmtUSD(yearOneInterest)}</b> goes to interest — only <b>{fmtUSD(result.piMonthly * 12 - yearOneInterest)}</b> reduces principal. That ratio flips around year {Math.round(inputs.termYears * 0.6)}.</>,
    },
    {
      icon: "sparkle",
      title: "+$200/mo to principal",
      body: <>Adding <b>$200/mo</b> to principal would save <b>{fmtUSD(extra200.interestSaved)}</b> in interest and pay off <b>{Math.floor(extra200.monthsSaved / 12)} yr {extra200.monthsSaved % 12} mo</b> earlier.</>,
    },
    {
      icon: "info",
      title: "Total interest vs. home price",
      body: <>You'll pay <b>{fmtPct(interestRatio, 0)}</b> of the loan amount in interest over the life of the loan ({fmtUSD(result.totalInterest)}).</>,
    },
  ];

  return (
    <div className="dc-card" style={{ padding: 20 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 4 }}>
        <span style={{ width: 24, height: 24, borderRadius: 6, background: "var(--accent-soft)", color: "var(--accent)", display: "inline-flex", alignItems: "center", justifyContent: "center" }}>
          <Icon name="sparkle" size={14} />
        </span>
        <h3 style={{ margin: 0, fontSize: 14, fontWeight: 600 }}>Explain my result</h3>
        <span className="dc-pill" style={{ marginLeft: "auto", fontSize: 10, padding: "1px 7px" }}>AI</span>
      </div>
      <p style={{ color: "var(--muted)", fontSize: 13, margin: "0 0 16px" }}>
        Three things worth noticing, given your inputs.
      </p>
      <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 14 }}>
        {pulls.map((p, i) => (
          <li key={i} style={{ display: "grid", gridTemplateColumns: "20px 1fr", gap: 10 }}>
            <span style={{ color: "var(--accent)", marginTop: 2 }}><Icon name={p.icon} size={14} /></span>
            <div>
              <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 2 }}>{p.title}</div>
              <div style={{ fontSize: 13, color: "var(--ink-2)", lineHeight: 1.55 }}>{p.body}</div>
            </div>
          </li>
        ))}
      </ul>
      <div style={{ marginTop: 16, paddingTop: 14, borderTop: "1px solid var(--rule)", display: "flex", gap: 8, alignItems: "center" }}>
        <input
          placeholder="Ask a follow-up about your result…"
          style={{
            flex: 1, border: "1px solid var(--rule)", borderRadius: 8, padding: "8px 12px",
            fontSize: 13, fontFamily: "var(--font-ui)", background: "var(--bg)", color: "var(--ink)",
            outline: 0,
          }}
        />
        <button className="dc-btn sm primary">Ask</button>
      </div>
    </div>
  );
};

/* ---------- Methodology drawer ---------- */
const Methodology = () => {
  const [open, setOpen] = useState(false);
  return (
    <div className="dc-card" style={{ padding: 0 }}>
      <button
        onClick={() => setOpen(!open)}
        style={{
          width: "100%", padding: "16px 20px", display: "flex", alignItems: "center",
          gap: 10, background: "transparent", border: 0, color: "inherit", cursor: "pointer",
          fontFamily: "var(--font-ui)",
        }}
      >
        <span style={{ flex: 1, textAlign: "left" }}>
          <div style={{ fontSize: 14, fontWeight: 600 }}>How we calculate this</div>
          <div style={{ fontSize: 12, color: "var(--muted)", marginTop: 2 }}>
            Standard amortization formula · principal &amp; interest only by default
          </div>
        </span>
        <Icon name="chevdown" size={16} style={{ color: "var(--muted)", transform: open ? "rotate(180deg)" : "none", transition: "transform var(--t-fast)" }} />
      </button>
      {open && (
        <div style={{ padding: "0 20px 20px", borderTop: "1px solid var(--rule)" }}>
          <p style={{ fontSize: 13.5, color: "var(--ink-2)", lineHeight: 1.6, marginTop: 14 }}>
            Monthly principal &amp; interest is calculated using the standard amortization formula:
          </p>
          <pre style={{
            fontFamily: "var(--font-mono)", fontSize: 12.5, padding: 14,
            background: "var(--surface-2)", borderRadius: 8, overflowX: "auto",
            margin: "8px 0 14px", color: "var(--ink-2)",
          }}>
{`M = P · [ r(1 + r)ⁿ / ((1 + r)ⁿ − 1) ]

P = principal (price − down payment)
r = monthly rate (APR / 12)
n = term in months (years · 12)`}
          </pre>
          <p style={{ fontSize: 13.5, color: "var(--ink-2)", lineHeight: 1.6, margin: 0 }}>
            Property tax and insurance, when supplied, are added as monthly amounts (annual ÷ 12). PMI (Private Mortgage Insurance) is typically required when your down payment is below 20% of the home price; typical rates run 0.2–2% of the loan per year. Toggle it on in the advanced section to include it. Estimates are for planning only; lenders may include additional fees.
          </p>
        </div>
      )}
    </div>
  );
};

/* ---------- main page ---------- */
const Calc = () => {
  const [price, setPrice] = useState(425000);
  const [downPct, setDownPct] = useState(20);
  const [ratePct, setRatePct] = useState(6.85);
  const [termYears, setTermYears] = useState(30);
  const [advanced, setAdvanced] = useState({ taxYr: 0, hoaMo: 0, insYr: 0 });
  const [pmiEnabled, setPmiEnabled] = useState(false);
  const [pmiRate, setPmiRate] = useState(0.85);

  const result = useMemo(
    () => calcMortgage({ price, downPct, ratePct, termYears, ...advanced, pmiEnabled, pmiRate }),
    [price, downPct, ratePct, termYears, advanced, pmiEnabled, pmiRate]
  );

  return (
    <div className="dc-shell" style={{ paddingTop: 32, paddingBottom: 80 }}>
      {/* breadcrumb */}
      <div style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 13, color: "var(--muted)", marginBottom: 18 }}>
        <a href="/" style={{ color: "var(--muted)" }}>All calculators</a>
        <Icon name="chevright" size={12} />
        <a href="#" onClick={(e) => e.preventDefault()} style={{ color: "var(--muted)" }}>Finance</a>
        <Icon name="chevright" size={12} />
        <span style={{ color: "var(--ink)" }}>Mortgage</span>
      </div>

      {/* Title row */}
      <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 16, flexWrap: "wrap", marginBottom: 24 }}>
        <div>
          <h1 style={{ fontFamily: "var(--font-display)", fontSize: 36, fontWeight: 700, letterSpacing: "-.02em", margin: 0, lineHeight: 1.05 }}>
            Mortgage Calculator
          </h1>
          <p style={{ color: "var(--muted)", fontSize: 15, margin: "6px 0 0", maxWidth: 540 }}>
            Drag the sliders, or type a number. Your monthly payment updates live.
          </p>
        </div>
        <div style={{ display: "flex", gap: 8 }}>
          <button className="dc-btn"><Icon name="bookmark" size={14} /> Save</button>
          <button className="dc-btn"><Icon name="share" size={14} /> Share</button>
          <button className="dc-btn"><Icon name="code" size={14} /> Embed</button>
          <button className="dc-iconbtn" aria-label="Print"><Icon name="print" size={14} /></button>
        </div>
      </div>

      {/* main grid */}
      <div className="calc-grid">
        {/* hero result */}
        <section className="calc-hero dc-card">
          <div className="calc-hero-main">
            <div className="dc-eyebrow">Your monthly payment</div>
            <div className="display num" style={{ fontSize: 96, color: "var(--accent)", marginTop: 8, marginBottom: 10 }}>
              {fmtUSD(result.totalMo)}
            </div>
            <div style={{ fontSize: 14, color: "var(--muted)" }}>
              <span className="num">{fmtUSD(result.totalInterest)}</span> total interest
              <span style={{ margin: "0 10px", color: "var(--rule-strong)" }}>·</span>
              paid off <span className="num">{fmtMonth(result.payoff)}</span>
              <span style={{ margin: "0 10px", color: "var(--rule-strong)" }}>·</span>
              <span className="num">{fmtUSD(result.totalPaid)}</span> total
            </div>
          </div>
          <div className="calc-hero-chart">
            <Donut
              size={150}
              values={[
                { value: result.principal, color: "var(--accent)" },
                { value: result.totalInterest, color: "var(--surface-2)" },
              ]}
            />
            <div className="calc-hero-legend">
              <div><span className="sw" style={{ background: "var(--accent)" }}></span>Principal <b className="num">{fmtUSD(result.principal)}</b></div>
              <div><span className="sw" style={{ background: "var(--rule-strong)" }}></span>Interest <b className="num">{fmtUSD(result.totalInterest)}</b></div>
            </div>
          </div>
        </section>

        {/* inputs */}
        <section className="calc-inputs dc-card">
          <div className="calc-section-head">
            <div className="dc-eyebrow">Inputs</div>
            <span style={{ fontSize: 12, color: "var(--faint)" }}>drag · or type</span>
          </div>

          <SliderRow
            label="Home price"
            value={price}
            onChange={setPrice}
            min={50000} max={2000000} step={1000}
            format={(v) => fmtUSD(v)}
          />
          <SliderRow
            label="Down payment"
            value={downPct}
            onChange={setDownPct}
            min={0} max={50} step={0.5}
            format={(v) => v.toFixed(1)}
            unit="%"
            hint={fmtUSD(price * (downPct / 100)) + " • loan: " + fmtUSD(price - price * (downPct / 100))}
          />
          <SliderRow
            label="Interest rate"
            value={ratePct}
            onChange={setRatePct}
            min={0.5} max={12} step={0.05}
            format={(v) => v.toFixed(2)}
            unit="%"
            hint="US 30-yr avg: 6.85%"
          />
          <SliderRow
            label="Loan term"
            value={termYears}
            onChange={(v) => setTermYears(Math.round(v))}
            min={5}
            max={40}
            step={1}
            unit="years"
            hint="Years"
          />

          <hr className="dc-divider" style={{ margin: "8px 0" }} />

          <details className="calc-advanced">
            <summary>
              <Icon name="plus" size={14} />
              <span>Add property tax, HOA, insurance, PMI</span>
            </summary>
            <div className="adv-grid">
              <SliderRow
                label="Property tax"
                value={advanced.taxYr}
                onChange={(v) => setAdvanced({ ...advanced, taxYr: v })}
                min={0} max={30000} step={100}
                format={(v) => fmtUSD(v)}
                unit="/ yr"
              />
              <SliderRow
                label="HOA"
                value={advanced.hoaMo}
                onChange={(v) => setAdvanced({ ...advanced, hoaMo: v })}
                min={0} max={2000} step={10}
                format={(v) => fmtUSD(v)}
                unit="/ mo"
              />
              <SliderRow
                label="Insurance"
                value={advanced.insYr}
                onChange={(v) => setAdvanced({ ...advanced, insYr: v })}
                min={0} max={10000} step={50}
                format={(v) => fmtUSD(v)}
                unit="/ yr"
              />
              <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "6px 0" }}>
                <span style={{ flex: 1, fontSize: 13.5, color: "var(--ink-2)" }}>PMI</span>
                {downPct < 20 && !pmiEnabled && (
                  <span style={{ fontSize: 11, color: "var(--warn)" }}>required &lt;20% down</span>
                )}
                <button
                  className={"sr-seg" + (pmiEnabled ? " active" : "")}
                  onClick={() => setPmiEnabled(!pmiEnabled)}
                  style={{ minWidth: 44 }}
                >
                  {pmiEnabled ? "On" : "Off"}
                </button>
              </div>
              {pmiEnabled && (
                <SliderRow
                  label="PMI rate"
                  value={pmiRate}
                  onChange={setPmiRate}
                  min={0.1} max={2} step={0.05}
                  format={(v) => v.toFixed(2)}
                  unit="% / yr"
                  hint={fmtUSD(result.pmiMo) + " / mo"}
                />
              )}
            </div>
          </details>
        </section>

        {/* Right rail: explain + methodology + breakdown */}
        <aside className="calc-aside">
          <ExplainPanel result={result} inputs={{ ratePct, termYears }} />
          <div className="dc-card" style={{ padding: 20 }}>
            <div className="dc-eyebrow" style={{ marginBottom: 12 }}>Monthly breakdown</div>
            <BreakdownRow lbl="Principal &amp; interest" val={fmtUSDc(result.piMonthly)} />
            {result.taxMo > 0 && <BreakdownRow lbl="Property tax" val={fmtUSDc(result.taxMo)} />}
            {result.insMo > 0 && <BreakdownRow lbl="Insurance" val={fmtUSDc(result.insMo)} />}
            {result.hoaMo > 0 && <BreakdownRow lbl="HOA" val={fmtUSDc(result.hoaMo)} />}
            {result.pmiMo > 0 && <BreakdownRow lbl="PMI" val={fmtUSDc(result.pmiMo)} />}
            <hr className="dc-divider" style={{ margin: "10px 0" }} />
            <BreakdownRow lbl={<b>Total / month</b>} val={<b>{fmtUSDc(result.totalMo)}</b>} />
          </div>
          <Methodology />
        </aside>
      </div>

      {/* Related */}
      <section style={{ marginTop: 56, paddingTop: 32, borderTop: "1px solid var(--rule)" }}>
        <h2 style={{ fontSize: 15, fontWeight: 600, margin: "0 0 14px", letterSpacing: "-.005em" }}>
          More finance calculators
        </h2>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(200px, 1fr))", gap: 10 }}>
          {["Auto Loan", "Compound Interest", "Retirement", "Refinance", "Loan Comparison"].map((n) => (
            <a key={n} href="#" onClick={(e) => e.preventDefault()} className="dc-card" style={{
              padding: 14, fontSize: 14, fontWeight: 500, display: "flex", alignItems: "center",
              transition: "border-color var(--t-fast)",
            }}
              onMouseEnter={(e) => e.currentTarget.style.borderColor = "var(--rule-strong)"}
              onMouseLeave={(e) => e.currentTarget.style.borderColor = "var(--rule)"}
            >
              <span style={{ flex: 1 }}>{n}</span>
              <Icon name="arrow" size={14} style={{ color: "var(--muted)" }} />
            </a>
          ))}
        </div>
      </section>
    </div>
  );
};
window.Calc = Calc;
window.Donut = Donut;

const BreakdownRow = ({ lbl, val }) => (
  <div style={{ display: "flex", justifyContent: "space-between", padding: "6px 0", fontSize: 13.5 }}>
    <span style={{ color: "var(--ink-2)" }}>{lbl}</span>
    <span className="num" style={{ color: "var(--ink)" }}>{val}</span>
  </div>
);
