/* Finance Family — Calculators (borrowing power, repayments, stamp duty, refinance).
   Each calculator shows a live result and flows into a soft lead-capture. */
(function () {
  const AUD = (n) => "$" + Math.round(n).toLocaleString("en-AU");
  const AUD2 = (n) => "$" + n.toLocaleString("en-AU", { maximumFractionDigits: 0 });

  function pmt(P, annualRate, years, perYear) {
    const r = annualRate / 100 / perYear;
    const n = years * perYear;
    if (r === 0) return P / n;
    return (P * r) / (1 - Math.pow(1 + r, -n));
  }

  // ---- Result + lead capture wrapper ----
  function ResultPanel({ children, ctaLabel }) {
    const { Button } = window.FinanceFamilyDesignSystem_66efc3;
    const Icon = window.Icon;
    return (
      <div style={{ padding: "clamp(20px,3vw,28px)", borderRadius: "var(--radius-lg)", background: "var(--blue-10)", border: "1.5px solid var(--blue-20)" }}>
        {children}
        <div style={{ marginTop: 20, paddingTop: 18, borderTop: "1.5px dashed var(--blue-20)", display: "flex", alignItems: "center", justifyContent: "space-between", gap: 16, flexWrap: "wrap" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10, fontFamily: "var(--font-body)", fontSize: 13.5, color: "var(--blue-deep)", maxWidth: 320 }}>
            <Icon name="shield" size={18} color="var(--brand-primary)" /> Want this checked against 40+ lenders? There's no cost to chat.
          </div>
          <a href="/book" style={{ textDecoration: "none" }}>
            <Button size="sm" iconRight={<Icon name="arrowRight" size={16} />}>{ctaLabel || "Get it checked"}</Button>
          </a>
        </div>
      </div>
    );
  }

  function Field({ label, children, hint }) {
    return (
      <div>
        <div style={{ fontFamily: "var(--font-body)", fontSize: 14, fontWeight: 600, color: "var(--text-strong)", marginBottom: 7 }}>{label}</div>
        {children}
        {hint && <div style={{ fontFamily: "var(--font-body)", fontSize: 12.5, color: "var(--text-muted)", marginTop: 6 }}>{hint}</div>}
      </div>
    );
  }

  function Stat({ label, value, big, accent }) {
    return (
      <div>
        <div style={{ fontFamily: "var(--font-eyebrow)", fontWeight: 700, fontSize: 11, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--blue-deep)" }}>{label}</div>
        <div style={{ fontFamily: "var(--font-display)", fontSize: big ? "clamp(32px,4.5vw,44px)" : 22, color: accent ? "var(--brand-primary)" : "var(--text-strong)", lineHeight: 1.05, marginTop: 4 }}>{value}</div>
      </div>
    );
  }

  // ---- 1. Borrowing power ----
  function BorrowingPower() {
    const { Input, Select } = window.FinanceFamilyDesignSystem_66efc3;
    const [income, setIncome] = React.useState(130000);
    const [deposit, setDeposit] = React.useState(80000);
    const [expenses, setExpenses] = React.useState(2500);
    const [deps, setDeps] = React.useState("0");
    const d = Number(deps);
    const factor = 5.6 - d * 0.4;
    const borrow = Math.max(0, income * factor - expenses * 12 * 1.5 - d * 9000);
    const budget = borrow + deposit;
    const repay = pmt(borrow, 5.94, 30, 12);
    return (
      <div className="calc-cols">
        <div className="stack" style={{ gap: 18 }}>
          <Field label="Combined annual income (before tax)">
            <Input type="number" value={income} onChange={(e) => setIncome(Number(e.target.value) || 0)} iconLeft={<span style={{ fontFamily: "var(--font-display)", color: "var(--navy-40)" }}>$</span>} />
          </Field>
          <Field label="Deposit saved">
            <Input type="number" value={deposit} onChange={(e) => setDeposit(Number(e.target.value) || 0)} iconLeft={<span style={{ fontFamily: "var(--font-display)", color: "var(--navy-40)" }}>$</span>} />
          </Field>
          <Field label="Monthly living expenses" hint="Rent, bills, groceries, repayments (excl. the new loan).">
            <Input type="number" value={expenses} onChange={(e) => setExpenses(Number(e.target.value) || 0)} iconLeft={<span style={{ fontFamily: "var(--font-display)", color: "var(--navy-40)" }}>$</span>} />
          </Field>
          <Field label="Dependants">
            <Select value={deps} onChange={(e) => setDeps(e.target.value)} options={["0", "1", "2", "3", "4"]} />
          </Field>
        </div>
        <ResultPanel ctaLabel="Confirm my real number">
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", gap: 16, flexWrap: "wrap" }}>
            <Stat label="You could borrow up to" value={AUD(borrow)} big />
            <Stat label="Property budget" value={AUD(budget)} accent />
          </div>
          <div style={{ height: 8, borderRadius: 999, background: "#fff", marginTop: 18, overflow: "hidden" }}><div style={{ width: Math.min(100, (borrow / 1200000) * 100) + "%", height: "100%", background: "var(--brand-primary)", borderRadius: 999 }} /></div>
          <div style={{ fontFamily: "var(--font-body)", fontSize: 13, color: "var(--text-muted)", marginTop: 12 }}>≈ {AUD(repay)}/month over 30 years at 5.94% p.a. · indicative only, not a loan offer.</div>
        </ResultPanel>
      </div>
    );
  }

  // ---- 2. Repayments ----
  function Repayments() {
    const { Input, Select } = window.FinanceFamilyDesignSystem_66efc3;
    const [amount, setAmount] = React.useState(550000);
    const [rate, setRate] = React.useState(5.94);
    const [term, setTerm] = React.useState(30);
    const [freq, setFreq] = React.useState("Monthly");
    const perYear = freq === "Weekly" ? 52 : freq === "Fortnightly" ? 26 : 12;
    const pay = pmt(amount, rate, term, perYear);
    const totalPaid = pay * perYear * term;
    const interest = totalPaid - amount;
    return (
      <div className="calc-cols">
        <div className="stack" style={{ gap: 18 }}>
          <Field label="Loan amount">
            <Input type="number" value={amount} onChange={(e) => setAmount(Number(e.target.value) || 0)} iconLeft={<span style={{ fontFamily: "var(--font-display)", color: "var(--navy-40)" }}>$</span>} />
          </Field>
          <div className="calc-row2">
            <Field label="Interest rate (% p.a.)"><Input type="number" value={rate} onChange={(e) => setRate(Number(e.target.value) || 0)} /></Field>
            <Field label="Term (years)"><Input type="number" value={term} onChange={(e) => setTerm(Number(e.target.value) || 1)} /></Field>
          </div>
          <Field label="Repayment frequency">
            <Select value={freq} onChange={(e) => setFreq(e.target.value)} options={["Weekly", "Fortnightly", "Monthly"]} />
          </Field>
        </div>
        <ResultPanel ctaLabel="Find me a sharper rate">
          <Stat label={freq + " repayment"} value={AUD(pay)} big />
          <div style={{ display: "flex", gap: 28, marginTop: 18, flexWrap: "wrap" }}>
            <Stat label="Total interest" value={AUD(interest)} />
            <Stat label="Total repaid" value={AUD(totalPaid)} />
          </div>
          <div style={{ fontFamily: "var(--font-body)", fontSize: 13, color: "var(--text-muted)", marginTop: 14 }}>Indicative only. A small rate change can save thousands — we'll hunt one down for you.</div>
        </ResultPanel>
      </div>
    );
  }

  // ---- 3. Stamp duty (simplified, indicative) ----
  function StampDuty() {
    const { Input, Select, Checkbox } = window.FinanceFamilyDesignSystem_66efc3;
    const [price, setPrice] = React.useState(750000);
    const [state, setState] = React.useState("VIC");
    const [fhb, setFhb] = React.useState(true);
    // very rough indicative duty
    const baseRate = { VIC: 0.055, NSW: 0.05, QLD: 0.0475, SA: 0.05, WA: 0.0485, TAS: 0.04, ACT: 0.045, NT: 0.0495 }[state];
    let duty = price * baseRate;
    let note = "Indicative general rate.";
    if (fhb && state === "VIC") {
      if (price <= 600000) { duty = 0; note = "VIC first-home exemption (≤ $600k)."; }
      else if (price <= 750000) { duty = duty * ((price - 600000) / 150000); note = "VIC first-home concession ($600k–$750k)."; }
    } else if (fhb && price <= 650000) { duty = duty * 0.5; note = "First-home concession (indicative)."; }
    return (
      <div className="calc-cols">
        <div className="stack" style={{ gap: 18 }}>
          <Field label="Property price">
            <Input type="number" value={price} onChange={(e) => setPrice(Number(e.target.value) || 0)} iconLeft={<span style={{ fontFamily: "var(--font-display)", color: "var(--navy-40)" }}>$</span>} />
          </Field>
          <Field label="State / territory">
            <Select value={state} onChange={(e) => setState(e.target.value)} options={["VIC", "NSW", "QLD", "SA", "WA", "TAS", "ACT", "NT"]} />
          </Field>
          <Checkbox label="I'm a first home buyer" checked={fhb} onChange={(e) => setFhb(e.target.checked)} />
        </div>
        <ResultPanel ctaLabel="Get the exact figure">
          <Stat label="Estimated stamp duty" value={AUD(duty)} big />
          <div style={{ fontFamily: "var(--font-body)", fontSize: 13, color: "var(--text-muted)", marginTop: 14 }}>{note} Real duty depends on current state rules, property use and concessions — we'll confirm to the dollar.</div>
        </ResultPanel>
      </div>
    );
  }

  // ---- 4. Refinance savings ----
  function Refinance() {
    const { Input } = window.FinanceFamilyDesignSystem_66efc3;
    const [balance, setBalance] = React.useState(520000);
    const [years, setYears] = React.useState(27);
    const [cur, setCur] = React.useState(6.59);
    const [neu, setNeu] = React.useState(5.84);
    const payCur = pmt(balance, cur, years, 12);
    const payNew = pmt(balance, neu, years, 12);
    const monthly = Math.max(0, payCur - payNew);
    const lifetime = monthly * years * 12;
    return (
      <div className="calc-cols">
        <div className="stack" style={{ gap: 18 }}>
          <Field label="Current loan balance">
            <Input type="number" value={balance} onChange={(e) => setBalance(Number(e.target.value) || 0)} iconLeft={<span style={{ fontFamily: "var(--font-display)", color: "var(--navy-40)" }}>$</span>} />
          </Field>
          <Field label="Years remaining"><Input type="number" value={years} onChange={(e) => setYears(Number(e.target.value) || 1)} /></Field>
          <div className="calc-row2">
            <Field label="Current rate (%)"><Input type="number" value={cur} onChange={(e) => setCur(Number(e.target.value) || 0)} /></Field>
            <Field label="New rate (%)"><Input type="number" value={neu} onChange={(e) => setNeu(Number(e.target.value) || 0)} /></Field>
          </div>
        </div>
        <ResultPanel ctaLabel="See if I can switch">
          <Stat label="You could save" value={AUD(monthly) + "/mo"} big accent />
          <div style={{ display: "flex", gap: 28, marginTop: 18, flexWrap: "wrap" }}>
            <Stat label="Over the loan" value={AUD(lifetime)} />
            <Stat label="New repayment" value={AUD(payNew) + "/mo"} />
          </div>
          <div style={{ fontFamily: "var(--font-body)", fontSize: 13, color: "var(--text-muted)", marginTop: 14 }}>Before switch costs. We'll factor in fees and tell you honestly if it's worth it.</div>
        </ResultPanel>
      </div>
    );
  }

  const TABS = [
    { value: "borrow", label: "Borrowing power", node: BorrowingPower, ic: "trending", blurb: "How much could you borrow?" },
    { value: "repay", label: "Repayments", node: Repayments, ic: "calculator", blurb: "What will it cost each month?" },
    { value: "stamp", label: "Stamp duty", node: StampDuty, ic: "fileText", blurb: "Estimate your government duty." },
    { value: "refi", label: "Refinance savings", node: Refinance, ic: "refresh", blurb: "Could switching save you money?" },
  ];

  function Calculators() {
    const { Tabs, Card } = window.FinanceFamilyDesignSystem_66efc3;
    const Icon = window.Icon;
    const hashTab = () => { const h = (window.location.hash || "").replace("#", ""); return TABS.some((t) => t.value === h) ? h : "borrow"; };
    const [tab, setTab] = React.useState(hashTab);
    React.useEffect(() => {
      const onHash = () => setTab(hashTab());
      window.addEventListener("hashchange", onHash);
      return () => window.removeEventListener("hashchange", onHash);
    }, []);
    const changeTab = (v) => { setTab(v); if (history.replaceState) history.replaceState(null, "", "#" + v); };
    const active = TABS.find((t) => t.value === tab);
    const Node = active.node;
    return (
      <React.Fragment>
        <window.SiteHeader page="calculators" />
        <main>
          <section style={{ background: "linear-gradient(180deg,var(--grey-40),#fff)" }}>
            <div className="container" style={{ paddingTop: "clamp(48px,5vw,80px)", paddingBottom: 36, textAlign: "center" }}>
              <window.Eyebrow>Free tools</window.Eyebrow>
              <h1 className="ff-display" style={{ fontSize: "clamp(2.2rem,1.6rem+3vw,3.4rem)", lineHeight: 1.12, margin: "16px auto 18px", maxWidth: 760 }}>Run the numbers in seconds.</h1>
              <p className="ff-lead muted" style={{ maxWidth: 560, margin: "0 auto" }}>Ballpark figures you can trust — then let a real broker turn them into a lender-checked plan.</p>
            </div>
          </section>
          <section className="section" style={{ paddingTop: 0 }}>
            <div className="container-narrow">
              <div style={{ display: "flex", justifyContent: "center", marginBottom: 8, overflowX: "auto" }}>
                <Tabs tabs={TABS.map((t) => ({ value: t.value, label: t.label }))} value={tab} onChange={changeTab} />
              </div>
              <Card padding="lg" style={{ marginTop: 24 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 24 }}>
                  <span style={{ width: 52, height: 52, borderRadius: "var(--radius-md)", background: "var(--blue-10)", display: "inline-flex", alignItems: "center", justifyContent: "center", flex: "none" }}>
                    <Icon name={active.ic} size={26} color="var(--brand-primary)" />
                  </span>
                  <div>
                    <h2 className="ff-h3" style={{ margin: 0 }}>{active.label}</h2>
                    <div className="muted" style={{ fontFamily: "var(--font-body)", fontSize: 14 }}>{active.blurb}</div>
                  </div>
                </div>
                <Node />
              </Card>
              <p className="center muted" style={{ fontFamily: "var(--font-body)", fontSize: 12.5, marginTop: 18, maxWidth: 620, marginLeft: "auto", marginRight: "auto" }}>
                Calculators provide indicative estimates only and are not financial or credit advice, nor a loan offer. Figures depend on lender policies and your full circumstances.
              </p>
            </div>
          </section>
        </main>
        <window.SiteFooter />
      </React.Fragment>
    );
  }
  window.Calculators = Calculators;
})();
