/* global React, RENDEMENT_DATA, computeRendement, computeAllScenarios, rcSuggestedPrice, rcMarketRent, Footer, BigCTA */
/* =============================================================================
   VIA Vastgoed — Rendementscalculator v2  ·  UI
   Route: /rendement   ·   Interface language: English (per brief)
   Business logic lives in rendement-logic.js, data in rendement-data.js.
   ============================================================================= */
const { useState, useMemo, useCallback, useEffect } = React;

const RC_DATA = (typeof RENDEMENT_DATA !== "undefined" ? RENDEMENT_DATA : window.RENDEMENT_DATA);

const rcEUR = (n) =>
  new Intl.NumberFormat("nl-NL", { style: "currency", currency: "EUR", maximumFractionDigits: 0 }).format(
    isFinite(n) ? n : 0
  );
const rcPct = (n) => (isFinite(n) ? (n * 100).toFixed(1) + "%" : "—");
const rcYears = (n) => (n == null || !isFinite(n) ? "—" : n.toFixed(1) + " yr");

const RC_SCENARIOS = [
  { key: "conservative", label: "Conservative" },
  { key: "realistic", label: "Realistic" },
  { key: "optimistic", label: "Optimistic" },
];

const RC_CMP_ROWS = [
  { label: "Annual rent", fmt: rcEUR, pick: (r) => r.grossAnnualRent },
  { label: "Net annual income", fmt: rcEUR, pick: (r) => r.netAnnualIncome },
  { label: "Gross yield", fmt: rcPct, pick: (r) => r.grossYield },
  { label: "Net yield", fmt: rcPct, pick: (r) => r.netYield },
  { label: "Payback", fmt: rcYears, pick: (r) => r.paybackYears },
];

function RcField({ label, help, children }) {
  return (
    <div className="rc-field">
      <label className="rc-label">{label}</label>
      {children}
      {help ? <p className="rc-help">{help}</p> : null}
    </div>
  );
}

/* Slider — exact dezelfde stijl als de FullCalculator (rode vulling links van thumb). */
function RcSlider({ min, max, step, value, onChange }) {
  const pct = Math.max(0, Math.min(100, ((value - min) / (max - min)) * 100));
  return (
    <div className="range-wrap">
      <div className="range-track"><div className="range-fill" style={{ width: pct + "%" }} /></div>
      <div className="range-thumb" style={{ left: pct + "%" }} />
      <input
        type="range"
        min={min}
        max={max}
        step={step}
        value={value}
        onChange={(e) => onChange(Number(e.target.value))}
        className="fc-range range-input"
      />
    </div>
  );
}

function RcMetric({ label, value, sub, big, negative }) {
  return (
    <div className={"rc-metric" + (big ? " rc-metric-big" : "")}>
      <span className="rc-metric-label">{label}</span>
      <span className={"rc-metric-value" + (negative ? " rc-neg" : "")}>{value}</span>
      {sub ? <span className="rc-metric-sub">{sub}</span> : null}
    </div>
  );
}

function RendementCalculator() {
  const defaults = RC_DATA.defaults;
  const locations = RC_DATA.locations;

  const [townName, setTownName] = useState(locations[0].townName);
  const [bedrooms, setBedrooms] = useState(2);
  const [rentalType, setRentalType] = useState("long");
  const [period, setPeriod] = useState("year");
  const [scenario, setScenario] = useState("realistic");
  const [financingEnabled, setFinancingEnabled] = useState(defaults.financing.enabledByDefault);
  const [ltv, setLtv] = useState(Math.round(defaults.financing.loanToValue * 100));
  const [interest, setInterest] = useState(defaults.financing.interestRate * 100);
  const [term, setTerm] = useState(defaults.financing.termYears);
  const [acqPct, setAcqPct] = useState(defaults.acquisitionCostPercent * 100);

  const location = useMemo(
    () => locations.find((l) => l.townName === townName) || locations[0],
    [locations, townName]
  );

  const [price, setPrice] = useState(() => rcSuggestedPrice(locations[0], 2, "long", defaults));

  // Basishuur (nachtprijs bij short / maandhuur bij long). Default = marktgemiddelde,
  // aanpasbaar door de gebruiker. Reset naar het marktgemiddelde als plaats / grootte /
  // verhuurtype wijzigt; blijft staan als alleen prijs of scenario verandert.
  const [rentBase, setRentBase] = useState(() => rcMarketRent(locations[0], 2, "long"));
  useEffect(() => {
    setRentBase(rcMarketRent(location, bedrooms, rentalType));
  }, [location, bedrooms, rentalType]);
  const marketRent = rcMarketRent(location, bedrooms, rentalType);
  const rentOverridden = Math.round(rentBase) !== Math.round(marketRent);

  const useSample = useCallback(() => {
    setPrice(rcSuggestedPrice(location, bedrooms, rentalType, defaults));
  }, [location, bedrooms, rentalType, defaults]);

  const baseOpts = useMemo(
    () => ({
      location,
      defaults,
      bedrooms,
      rentalType,
      purchasePrice: price,
      rentBase,
      financing: {
        enabled: financingEnabled,
        loanToValue: ltv / 100,
        interestRate: interest / 100,
        termYears: term,
      },
      acquisitionCostPercent: acqPct / 100,
    }),
    [location, defaults, bedrooms, rentalType, price, rentBase, financingEnabled, ltv, interest, term, acqPct]
  );

  const result = useMemo(() => computeRendement({ ...baseOpts, scenarioKey: scenario }), [baseOpts, scenario]);
  const allScenarios = useMemo(() => computeAllScenarios(baseOpts), [baseOpts]);

  const isShort = rentalType === "short";
  const rentHeadline = period === "month" ? rcEUR(result.monthlyRent) : rcEUR(result.grossAnnualRent);
  const rentHeadlineSub =
    period === "month"
      ? rcEUR(result.grossAnnualRent) + " / year"
      : rcEUR(result.monthlyRent) + " / month";

  const costRows = [
    { label: "Management fee", value: result.costs.management },
    ...(isShort ? [{ label: "Cleaning", value: result.costs.cleaning }] : []),
    { label: "Community fees", value: result.costs.community },
    { label: "IBI (property tax)", value: result.costs.ibi },
    { label: "Insurance", value: result.costs.insurance },
    { label: "Maintenance reserve", value: result.costs.maintenance },
    ...(result.costs.utilities > 0 ? [{ label: "Utilities", value: result.costs.utilities }] : []),
  ];

  return (
    <div className="rc-shell">
      {/* ---------------- INPUT PANEL ---------------- */}
      <div className="rc-panel rc-inputs">
        <div className="rc-panel-head">
          <span className="eyebrow"><span className="dot"></span>Your property</span>
        </div>

        <RcField label="Town" help="Costa del Sol location used for rent and cost estimates.">
          <select className="rc-select" value={townName} onChange={(e) => setTownName(e.target.value)}>
            {locations.map((l) => (
              <option key={l.townName} value={l.townName}>
                {l.townName} — {l.areaGroup}
              </option>
            ))}
          </select>
        </RcField>

        <div className="rc-row-2">
          <RcField label="Bedrooms" help="Apartment size.">
            <select className="rc-select" value={bedrooms} onChange={(e) => setBedrooms(Number(e.target.value))}>
              <option value={1}>1 bedroom</option>
              <option value={2}>2 bedrooms</option>
              <option value={3}>3 bedrooms</option>
            </select>
          </RcField>

          <RcField label="Rental type" help="Long stay = monthly tenant. Short stay = holiday lets.">
            <select className="rc-select" value={rentalType} onChange={(e) => setRentalType(e.target.value)}>
              <option value="long">Long stay</option>
              <option value="short">Short stay</option>
            </select>
          </RcField>
        </div>

        <RcField
          label={isShort ? "Nightly rate" : "Monthly rent"}
          help={
            "Market average for this town & size" +
            (rentOverridden ? " (adjusted)" : "") +
            ". Raise or lower it if this specific property is above or below average."
          }
        >
          <div className="rc-price-row">
            <div className="rc-input-eur">
              <span>€</span>
              <input
                type="number"
                className="rc-input"
                min={0}
                step={isShort ? 5 : 25}
                value={Math.round(rentBase)}
                onChange={(e) => setRentBase(Math.max(0, Number(e.target.value) || 0))}
              />
            </div>
            {rentOverridden ? (
              <button type="button" className="rc-sample-btn" onClick={() => setRentBase(marketRent)}>Reset</button>
            ) : null}
          </div>
        </RcField>

        <RcField
          label="Purchase price"
          help={"Sample value for this selection: " + rcEUR(rcSuggestedPrice(location, bedrooms, rentalType, defaults)) + "."}
        >
          <div className="rc-price-row">
            <div className="rc-input-eur">
              <span>€</span>
              <input
                type="number"
                className="rc-input"
                min={50000}
                step={5000}
                value={price}
                onChange={(e) => setPrice(Math.max(0, Number(e.target.value) || 0))}
              />
            </div>
            <button type="button" className="rc-sample-btn" onClick={useSample}>Use sample</button>
          </div>
          <RcSlider
            min={100000}
            max={2000000}
            step={5000}
            value={Math.min(2000000, Math.max(100000, price))}
            onChange={setPrice}
          />
        </RcField>

        <RcField label="Scenario" help="Adjusts occupancy and rent expectations.">
          <div className="rc-seg">
            {RC_SCENARIOS.map((s) => (
              <button
                key={s.key}
                type="button"
                className={"rc-seg-btn" + (scenario === s.key ? " is-active" : "")}
                onClick={() => setScenario(s.key)}
              >
                {s.label}
              </button>
            ))}
          </div>
        </RcField>

        {/* Financing */}
        <div className="rc-fin">
          <label className="rc-toggle">
            <input type="checkbox" checked={financingEnabled} onChange={(e) => setFinancingEnabled(e.target.checked)} />
            <span>Finance with a mortgage</span>
          </label>
          {financingEnabled ? (
            <div className="rc-fin-grid">
              <RcField label={"Loan-to-value (" + ltv + "%)"} help="Non-residents: max 70%.">
                <RcSlider min={0} max={70} step={5} value={ltv} onChange={setLtv} />
              </RcField>
              <div className="rc-row-2">
                <RcField label="Interest %" help="Indicative.">
                  <input type="number" className="rc-input" step={0.05} value={interest} onChange={(e) => setInterest(Number(e.target.value) || 0)} />
                </RcField>
                <RcField label="Term (years)" help="Mortgage duration.">
                  <input type="number" className="rc-input" step={1} value={term} onChange={(e) => setTerm(Number(e.target.value) || 0)} />
                </RcField>
              </div>
            </div>
          ) : null}
        </div>

        <details className="rc-advanced">
          <summary>Advanced assumptions</summary>
          <RcField label={"Acquisition costs (" + acqPct.toFixed(1) + "%)"} help="Costs on top of price. Resale ~10%, new-build ~14.2%.">
            <RcSlider min={5} max={16} step={0.1} value={acqPct} onChange={setAcqPct} />
          </RcField>
        </details>
      </div>

      {/* ---------------- RESULTS PANEL ---------------- */}
      <div className="rc-panel rc-results">
        <div className="rc-rent-head">
          <div>
            <span className="rc-metric-label">Estimated rent</span>
            <span className="rc-rent-value">{rentHeadline}</span>
            <span className="rc-metric-sub">{rentHeadlineSub}</span>
          </div>
          <div className="rc-seg rc-seg-sm">
            <button type="button" className={"rc-seg-btn" + (period === "month" ? " is-active" : "")} onClick={() => setPeriod("month")}>Month</button>
            <button type="button" className={"rc-seg-btn" + (period === "year" ? " is-active" : "")} onClick={() => setPeriod("year")}>Year</button>
          </div>
        </div>

        {isShort ? (
          <p className="rc-note-inline">
            Based on {rcPct(result.occupancyRate)} occupancy · {Math.round(result.nightsPerYear)} nights/year at {rcEUR(result.nightlyRate)}/night.
          </p>
        ) : null}
        <p className="rc-note-inline">
          Rent is set by the market ({isShort ? "nightly rate" : "monthly rent"}), not by the purchase price — so a lower price means a higher yield. Adjust the {isShort ? "nightly rate" : "rent"} on the left for a specific property.
        </p>

        <div className="rc-metric-grid">
          <RcMetric big label="Gross yield" value={rcPct(result.grossYield)} />
          <RcMetric big label="Net yield" value={rcPct(result.netYield)} negative={result.netYield < 0} />
          <RcMetric label="Net annual income" value={rcEUR(result.netAnnualIncome)} negative={result.netAnnualIncome < 0} />
          <RcMetric label="Payback period" value={rcYears(result.paybackYears)} sub="on cash invested" />
          <RcMetric label="Cash-on-cash" value={rcPct(result.cashOnCash)} negative={result.cashOnCash < 0} />
          {financingEnabled ? (
            <RcMetric label="Mortgage / month" value={rcEUR(result.mortgageMonthly)} />
          ) : (
            <RcMetric label="Cash invested" value={rcEUR(result.cashInvested)} />
          )}
        </div>

        {/* Seasonal breakdown (short stay only) */}
        {isShort && result.seasonal ? (
          <>
            <h3 className="rc-table-title">Seasonal breakdown</h3>
            <table className="rc-table">
              <thead>
                <tr>
                  <th>Season</th>
                  <th className="rc-num">Nightly rate</th>
                  <th className="rc-num">Occupancy</th>
                </tr>
              </thead>
              <tbody>
                {result.seasonal.seasons.map((s) => (
                  <tr key={s.key}>
                    <td>{s.label}</td>
                    <td className="rc-num">{rcEUR(s.nightly)}</td>
                    <td className="rc-num">{rcPct(s.occupancy)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
            {result.seasonal.peak ? (
              <p className="rc-note-inline">
                Peak month ({result.seasonal.peak.label}): ~{rcEUR(result.seasonal.peak.nightly)}/night. Market indication — the annual figures above use the yearly average.
              </p>
            ) : null}
          </>
        ) : null}

        {/* Cost breakdown */}
        <h3 className="rc-table-title">Annual cost breakdown</h3>
        <table className="rc-table">
          <tbody>
            {costRows.map((r) => (
              <tr key={r.label}>
                <td>{r.label}</td>
                <td className="rc-num">{rcEUR(r.value)}</td>
              </tr>
            ))}
            <tr className="rc-table-total">
              <td>Total operating costs</td>
              <td className="rc-num">{rcEUR(result.operatingCosts)}</td>
            </tr>
            <tr>
              <td>Tax reserve ({rcPct(defaults.taxReservePercent)})</td>
              <td className="rc-num">{rcEUR(result.taxReserve)}</td>
            </tr>
            {financingEnabled ? (
              <tr>
                <td>Mortgage (annual)</td>
                <td className="rc-num">{rcEUR(result.mortgageAnnual)}</td>
              </tr>
            ) : null}
          </tbody>
        </table>

        {/* Scenario comparison */}
        <h3 className="rc-table-title">Scenario comparison</h3>
        {/* Desktop: table */}
        <div className="rc-table-scroll rc-cmp-table">
          <table className="rc-table rc-table-compare">
            <thead>
              <tr>
                <th></th>
                {RC_SCENARIOS.map((s) => (
                  <th key={s.key} className={scenario === s.key ? "is-active" : ""}>{s.label}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {RC_CMP_ROWS.map((row) => (
                <tr key={row.label}>
                  <td>{row.label}</td>
                  {RC_SCENARIOS.map((s) => {
                    const val = row.pick(allScenarios[s.key]);
                    const neg = typeof val === "number" && val < 0;
                    return (
                      <td
                        key={s.key}
                        className={"rc-num" + (scenario === s.key ? " is-active" : "") + (neg ? " rc-neg" : "")}
                      >
                        {row.fmt(val)}
                      </td>
                    );
                  })}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        {/* Mobile: stacked cards (no horizontal overflow) */}
        <div className="rc-cmp-cards">
          {RC_SCENARIOS.map((s) => (
            <div key={s.key} className={"rc-cmp-card" + (scenario === s.key ? " is-active" : "")}>
              <div className="rc-cmp-card-head">{s.label}</div>
              {RC_CMP_ROWS.map((row) => {
                const val = row.pick(allScenarios[s.key]);
                const neg = typeof val === "number" && val < 0;
                return (
                  <div key={row.label} className="rc-cmp-card-row">
                    <span>{row.label}</span>
                    <span className={"rc-num" + (neg ? " rc-neg" : "")}>{row.fmt(val)}</span>
                  </div>
                );
              })}
            </div>
          ))}
        </div>

        <button type="button" className="rc-cta" onClick={() => window.openLeadGate && window.openLeadGate("kennismaking")}>
          Request a full investment analysis
        </button>

        <p className="rc-disclaimer">
          These figures are estimates for indicative purposes only, based on editable market assumptions per town. They are
          not a guarantee of rental income, yield or return, and do not constitute financial or tax advice. Actual results
          depend on the specific property, financing, taxes and market conditions.
        </p>
      </div>
    </div>
  );
}

function RendementPage() {
  return (
    <>
      <div className="calc-page-wrap">
        <div className="subhero-eye reveal-fade">
          <span className="eyebrow"><span className="dot"></span>Rental yield calculator</span>
        </div>
        <h1 className="reveal-fade" style={{ marginTop: "16px", "--reveal-delay": "0.1s" }}>
          Estimate your <em>return</em><br />on Spanish property
        </h1>
        <p className="rc-intro reveal-fade" style={{ "--reveal-delay": "0.15s" }}>
          Select a Costa del Sol town, property size and rental type to estimate rent, yield, cash flow and payback.
        </p>
        <RendementCalculator />
      </div>
      <BigCTA />
      <Footer />
    </>
  );
}

if (typeof window !== "undefined") window.RendementPage = RendementPage;
