// Solar ROI — responsive 2-column layout.

function SolarROI() {
  const { appliances, rate, solarInput, setSolarInput, tweaks, goBill } =
    React.useContext(window.AppContext);

  const applianceUnits = appliances.reduce((s, a) => {
    const h = hoursBetween(a.start, a.end);
    return s + (a.wattage * h * 30) / 1000;
  }, 0);

  const flatRate = rate.mode === "flat" ? rate.flat
    : window.computeBill(applianceUnits || 300, rate).effectiveRate || 35;

  let monthlyUnits;
  if (solarInput.source === "appliances") {
    monthlyUnits = applianceUnits;
  } else {
    const monthlyBill = solarInput.period === "annual"
      ? solarInput.billAmount / 12
      : solarInput.billAmount;
    monthlyUnits = monthlyBill / Math.max(1, flatRate);
  }

  const dailyUnits = monthlyUnits / 30;
  const systemKW = monthlyUnits / (30 * tweaks.irradiance * tweaks.performanceRatio);
  const installLow  = systemKW * tweaks.installCostLow;
  const installHigh = systemKW * tweaks.installCostHigh;
  const installMid  = (installLow + installHigh) / 2;
  const monthlySavings = monthlyUnits * flatRate;
  const paybackMonths = monthlySavings > 0 ? installMid / monthlySavings : 0;
  const lifetimeSavings = (monthlySavings * 12 * 25) - installMid;

  const hasInput = monthlyUnits > 0;

  // Track ROI calculation (debounced 1.5s after last change)
  React.useEffect(() => {
    if (!paybackMonths || paybackMonths <= 0) return;
    const t = setTimeout(() => {
      if (window.gtag) window.gtag('event', 'solar_roi_calculated', {
        payback_months: Math.round(paybackMonths),
        payback_category: paybackMonths < 48 ? 'good' : 'long',
      });
    }, 1500);
    return () => clearTimeout(t);
  }, [paybackMonths]);

  return (
    <>
      {/* HERO BAND */}
      <div className="hero-band">
        <div className="app-shell">
          <SolarHero systemKW={systemKW} units={monthlyUnits}
                     monthlySavings={monthlySavings} paybackMonths={paybackMonths}
                     hasInput={hasInput} currency={tweaks.currencySymbol}/>
        </div>
      </div>

      {/* TWO-COL BODY */}
      <div className="page-wrap">
        <div className="page-grid">
          {/* LEFT — inputs + details */}
          <div className="col col-pad">
            <Section title="Where's your usage from?"
                     hint="Pick whichever you have on hand">
              <Toggle full
                      options={[
                        { value: "appliances", label: `My ${appliances.length} appliance${appliances.length === 1 ? "" : "s"}` },
                        { value: "bill",       label: "A recent bill" },
                      ]}
                      value={solarInput.source}
                      onChange={(v) => setSolarInput({ ...solarInput, source: v })} />

              <div style={{ marginTop: 14 }}>
                {solarInput.source === "appliances" ? (
                  <ApplianceSummary units={applianceUnits} count={appliances.length}
                                    currency={tweaks.currencySymbol}
                                    onEdit={goBill} />
                ) : (
                  <BillInput solarInput={solarInput} setSolarInput={setSolarInput}
                             currency={tweaks.currencySymbol} />
                )}
              </div>
            </Section>

            {hasInput && (
              <Section title="How we got there"
                       hint="Show the math behind the recommendation">
                <StatRow label="Monthly consumption"
                         value={<span><span className="mono">{fmtUnits(monthlyUnits)}</span> units</span>} />
                <StatRow label="Daily consumption"
                         value={<span><span className="mono">{fmtUnits(dailyUnits)}</span> units/day</span>} />
                <StatRow label="Solar irradiance (PK avg)"
                         value={<span className="mono">{tweaks.irradiance} kWh/m²/day</span>}
                         hint="Editable in Tweaks" />
                <StatRow label="Performance ratio"
                         value={<span className="mono">{(tweaks.performanceRatio*100).toFixed(0)}%</span>}
                         hint="Real-world derate from losses" />
                <StatRow label="Effective rate / unit"
                         value={<span className="mono">{tweaks.currencySymbol} {flatRate.toFixed(2)}</span>} />
                <StatRow label="Recommended system"
                         value={<span><span className="mono">{systemKW.toFixed(2)}</span> kW</span>}
                         emphasis />
              </Section>
            )}

            {hasInput && (
              <Section style={{ borderBottom: "none" }}>
                <PrimaryButton full variant="primary" icon={<IconShare size={14}/>}
                  onClick={() => {
                    if (window.gtag) window.gtag('event', 'share_clicked', { calculator_type: 'solar' });
                    const txt = `My solar estimate: ${systemKW.toFixed(1)} kW system, ${tweaks.currencySymbol} ${fmtPKR(monthlySavings,{symbol:""}).trim()}/mo savings, pays back in ${paybackMonths.toFixed(0)} months. | Pak Bill Calculator`;
                    if (navigator.share) {
                      navigator.share({ title: "My solar estimate", text: txt }).catch(() => {});
                    } else if (navigator.clipboard) {
                      navigator.clipboard.writeText(txt);
                      alert("Copied to clipboard");
                    }
                  }}>
                  Share my estimate
                </PrimaryButton>
                {tweaks.showTips && (
                  <div style={{ marginTop: 12, padding: "10px 12px",
                                background: "var(--bg-2)", borderRadius: 10,
                                border: "1px solid var(--border-soft)",
                                fontSize: 12, color: "var(--muted)",
                                display: "flex", gap: 8, alignItems: "flex-start" }}>
                    <IconInfo size={13} style={{ flexShrink: 0, marginTop: 2 }}/>
                    <span>Estimates assume net-metering, no battery storage, and stable tariffs. A real solar quote will refine these numbers.</span>
                  </div>
                )}
              </Section>
            )}
          </div>

          {/* RIGHT — stats grid + chart */}
          <div className="col col-pad sticky-right">
            {hasInput ? (
              <>
                <Section title="The numbers"
                         hint="At today's rates and Pakistan irradiance">
                  <div className="stat-grid">
                    <StatCard label="Install cost" emph
                              value={`${tweaks.currencySymbol} ${fmtPKR(installLow,{symbol:"",compact:true}).trim()}–${fmtPKR(installHigh,{symbol:"",compact:true}).trim()}`}
                              sub="Panels + inverter + install"
                              tone="default"/>
                    <StatCard label="Monthly savings"
                              value={fmtPKR(monthlySavings, { symbol: tweaks.currencySymbol })}
                              sub={`@ ${tweaks.currencySymbol} ${flatRate.toFixed(1)}/unit`}
                              tone="solar"/>
                    <StatCard label="Pays back in"
                              value={paybackMonths > 0 ? `${paybackMonths.toFixed(0)} mo` : "N/A"}
                              sub={paybackMonths > 0 ? `~ ${(paybackMonths/12).toFixed(1)} years` : ""}
                              tone="accent"/>
                    <StatCard label="25-year savings"
                              value={fmtPKR(lifetimeSavings, { symbol: tweaks.currencySymbol, compact: true })}
                              sub="Net of install cost"
                              tone="default"/>
                  </div>
                </Section>

                <Section title="Payback curve"
                         hint="Cumulative savings vs install cost">
                  <PaybackChart install={installMid} monthlySavings={monthlySavings}
                                currency={tweaks.currencySymbol}/>
                </Section>

                <Section style={{ borderBottom: "none" }}>
                  <AdSlot slot="solar" style={{ margin: 0 }}/>
                </Section>
              </>
            ) : (
              <Section style={{ borderBottom: "none" }}>
                <div style={{
                  padding: "44px 20px", textAlign: "center",
                  border: "1px dashed var(--border)", borderRadius: "var(--radius)",
                  background: "var(--bg-2)",
                }}>
                  <div className="serif" style={{ fontSize: 24, color: "var(--fg-2)" }}>
                    Tell us a bill, get a system size.
                  </div>
                  <div style={{ fontSize: 13, color: "var(--muted)", marginTop: 10 }}>
                    Either add appliances on the Bill Calculator tab, or enter a recent bill on the left.
                  </div>
                </div>
              </Section>
            )}
          </div>
        </div>
      </div>
    </>
  );
}

// ---- Source summary -------------------------------------------------------

function ApplianceSummary({ units, count, currency, onEdit }) {
  return (
    <div style={{
      padding: 14, borderRadius: "var(--radius)",
      border: "1px solid var(--border-soft)", background: "var(--bg-2)",
      display: "flex", alignItems: "center", gap: 14,
    }}>
      <div style={{
        width: 44, height: 44, borderRadius: 12,
        background: "var(--surface)", border: "1px solid var(--border-soft)",
        display: "grid", placeItems: "center", color: "var(--fg-2)",
      }}>
        <IconList size={20} stroke={1.4}/>
      </div>
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 14, fontWeight: 500 }}>
          {count > 0 ? <>From <span className="mono">{count}</span> appliances</> : "No appliances yet"}
        </div>
        <div style={{ fontSize: 12, color: "var(--muted)", marginTop: 2 }}>
          <span className="mono">{fmtUnits(units)}</span> units/month total
        </div>
      </div>
      <button onClick={onEdit} style={{
        padding: "7px 11px", borderRadius: 999,
        fontSize: 12, fontWeight: 500, color: "var(--fg)",
        background: "var(--surface)", border: "1px solid var(--border)",
      }}>Edit list →</button>
    </div>
  );
}

function BillInput({ solarInput, setSolarInput, currency }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
      <Toggle options={[{ value: "monthly", label: "Monthly bill" }, { value: "annual", label: "Annual bill" }]}
              value={solarInput.period} full
              onChange={(v) => setSolarInput({ ...solarInput, period: v })}/>
      <NumberField large prefix={currency}
                   value={solarInput.billAmount}
                   step={500} min={0}
                   onChange={(v) => setSolarInput({ ...solarInput, billAmount: Number(v) || 0 })}/>
    </div>
  );
}

// ---- Hero -----------------------------------------------------------------

function SolarHero({ systemKW, units, monthlySavings, paybackMonths, hasInput, currency }) {
  const panels = systemKW > 0 ? Math.ceil(systemKW * 1.85) : 0;

  return (
    <div className="hero-row">
      <div>
        <div style={{ ...ss.label, marginBottom: 8 }}>Recommended system</div>
        <div style={{ display: "flex", alignItems: "baseline", gap: 10, flexWrap: "wrap" }}>
          <span className="mono" style={{ fontSize: 80, lineHeight: 1, fontWeight: 500,
                                           color: "var(--fg)", letterSpacing: "-0.03em" }}>
            {hasInput ? systemKW.toFixed(1) : "0.0"}
          </span>
          <span className="serif" style={{ fontSize: 36, color: "var(--fg-2)", fontStyle: "italic" }}>
            kW
          </span>
        </div>
        {hasInput ? (
          <div className="serif" style={{
            marginTop: 14, fontSize: 18, color: "var(--muted)",
            fontStyle: "italic", maxWidth: 460, lineHeight: 1.35,
          }}>
            Covers <span style={{ color: "var(--fg-2)" }}>{fmtUnits(units)}</span> units a month,
            roughly <span style={{ color: "var(--fg-2)" }}>{panels}</span> panels on your roof,
            paying back in <span style={{ color: "var(--fg-2)" }}>{paybackMonths.toFixed(0)} months</span>.
          </div>
        ) : (
          <div style={{ marginTop: 14, fontSize: 14, color: "var(--muted)", maxWidth: 460 }}>
            Enter a recent bill or use your appliance list to see the recommendation.
          </div>
        )}
      </div>

      <div style={{
        position: "relative", overflow: "hidden",
        padding: "20px 22px",
        background: "linear-gradient(180deg, oklch(0.99 0.025 80), var(--surface))",
        borderRadius: "var(--radius-lg)",
        border: "1px solid var(--border-soft)",
        boxShadow: "var(--shadow)",
        minHeight: 160,
      }}>
        <svg width="180" height="180" viewBox="0 0 180 180"
             style={{ position: "absolute", top: -30, right: -30, opacity: 0.7 }}>
          <g stroke="var(--accent)" strokeWidth="1" strokeLinecap="round" fill="none">
            {Array.from({length: 20}).map((_, i) => {
              const a = (i / 20) * Math.PI * 2;
              const r1 = 38, r2 = 78;
              return <line key={i} x1={90 + Math.cos(a)*r1} y1={90 + Math.sin(a)*r1}
                           x2={90 + Math.cos(a)*r2} y2={90 + Math.sin(a)*r2} />;
            })}
            <circle cx="90" cy="90" r="28" fill="var(--accent-soft)" stroke="var(--accent)" strokeWidth="1.5"/>
            <circle cx="90" cy="90" r="14" fill="var(--accent)" opacity="0.4" stroke="none"/>
          </g>
        </svg>
        <div style={{ position: "relative" }}>
          <div className="mono" style={{ fontSize: 10, color: "var(--muted)",
                                          textTransform: "uppercase", letterSpacing: "0.08em" }}>
            Saves
          </div>
          <div style={{ display: "flex", alignItems: "baseline", gap: 4, marginTop: 4 }}>
            <span className="mono" style={{ fontSize: 32, fontWeight: 600, color: "var(--solar-ink)", letterSpacing: "-0.02em" }}>
              {hasInput ? fmtPKR(monthlySavings, { symbol: currency, compact: true }) : "-"}
            </span>
            <span style={{ fontSize: 13, color: "var(--muted)" }}>/mo</span>
          </div>
          <div style={{ marginTop: 14, fontSize: 13, color: "var(--fg-2)" }}>
            <span className="mono" style={{ color: "var(--solar-ink)", fontWeight: 600 }}>
              → {panels || "-"}
            </span> panels needed
          </div>
          <div style={{ marginTop: 4, fontSize: 12, color: "var(--muted)" }}>
            Pakistan benchmark 550 W panels
          </div>
        </div>
      </div>
    </div>
  );
}

// ---- Mini stat card -------------------------------------------------------

function StatCard({ label, value, sub, tone = "default", emph }) {
  const tones = {
    default: { bg: "var(--surface)", border: "var(--border-soft)", accent: "var(--fg)" },
    accent:  { bg: "oklch(0.99 0.025 75)", border: "var(--accent-soft)", accent: "var(--accent-ink)" },
    solar:   { bg: "oklch(0.99 0.02 145)", border: "var(--solar-soft)", accent: "var(--solar-ink)" },
  };
  const t = tones[tone];
  return (
    <div style={{
      padding: 14,
      background: t.bg,
      border: `1px solid ${t.border}`,
      borderRadius: "var(--radius)",
      minHeight: 96,
      display: "flex", flexDirection: "column", justifyContent: "space-between",
    }}>
      <div style={ss.label}>{label}</div>
      <div className="mono" style={{
        fontSize: emph ? 17 : 22,
        fontWeight: 600,
        color: t.accent,
        letterSpacing: "-0.01em",
        marginTop: 8,
        lineHeight: 1.1,
      }}>{value}</div>
      {sub && <div style={{ fontSize: 11, color: "var(--muted)", marginTop: 4 }}>{sub}</div>}
    </div>
  );
}

// ---- Payback chart --------------------------------------------------------

function PaybackChart({ install, monthlySavings, currency }) {
  const months = 60;
  const w = 380, h = 160, padL = 0, padR = 0, padT = 12, padB = 24;
  const breakEvenMonth = monthlySavings > 0 ? install / monthlySavings : 0;
  const xMax = Math.max(months, breakEvenMonth * 1.15);
  const yMax = Math.max(install * 1.2, monthlySavings * months);

  const xs = (m) => (m / xMax) * (w - padL - padR) + padL;
  const ys = (v) => h - padB - (v / yMax) * (h - padT - padB);

  const savingsPts = [];
  for (let m = 0; m <= months; m += 1) {
    savingsPts.push(`${xs(m).toFixed(1)},${ys(m * monthlySavings).toFixed(1)}`);
  }

  return (
    <div style={{
      padding: 14, borderRadius: "var(--radius)",
      background: "var(--surface)", border: "1px solid var(--border-soft)",
    }}>
      <svg viewBox={`0 0 ${w} ${h}`} style={{ width: "100%", height: "auto", display: "block" }}>
        {[0.25, 0.5, 0.75, 1].map((p, i) => (
          <line key={i} x1={padL} x2={w-padR} y1={ys(yMax*p)} y2={ys(yMax*p)}
                stroke="var(--border-soft)" strokeWidth="0.5"/>
        ))}

        <line x1={padL} x2={w-padR} y1={ys(install)} y2={ys(install)}
              stroke="var(--fg-2)" strokeWidth="1" strokeDasharray="3 3"/>
        <text x={w-padR-4} y={ys(install)-6} textAnchor="end"
              fontFamily="var(--font-mono)" fontSize="10" fill="var(--fg-2)">
          install · {currency} {fmtPKR(install,{symbol:"",compact:true}).trim()}
        </text>

        <polygon points={`${padL},${h-padB} ${savingsPts.join(" ")} ${xs(months)},${h-padB}`}
                 fill="var(--solar)" opacity="0.08"/>
        <polyline points={savingsPts.join(" ")} fill="none"
                  stroke="var(--solar)" strokeWidth="2"
                  strokeLinejoin="round" strokeLinecap="round"/>

        {breakEvenMonth > 0 && breakEvenMonth < xMax && (
          <>
            <circle cx={xs(breakEvenMonth)} cy={ys(install)} r="4.5"
                    fill="var(--solar)" stroke="var(--surface)" strokeWidth="2"/>
            <line x1={xs(breakEvenMonth)} x2={xs(breakEvenMonth)}
                  y1={ys(install)} y2={h-padB}
                  stroke="var(--solar)" strokeWidth="0.5" strokeDasharray="2 2"/>
            <text x={xs(breakEvenMonth)} y={h-8} textAnchor="middle"
                  fontFamily="var(--font-mono)" fontSize="10" fill="var(--solar-ink)" fontWeight="600">
              ↑ {breakEvenMonth.toFixed(0)} mo
            </text>
          </>
        )}

        {[0, 12, 24, 36, 48, 60].map((m) => (
          <text key={m} x={xs(m)} y={h-8} textAnchor="middle"
                fontFamily="var(--font-mono)" fontSize="9"
                fill="var(--muted-2)">{m === 0 ? "0" : `${m}m`}</text>
        ))}
      </svg>
      <div style={{ display: "flex", gap: 14, marginTop: 10, fontSize: 11, color: "var(--muted)", flexWrap: "wrap" }}>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}>
          <span style={{ width: 14, height: 2, background: "var(--solar)", borderRadius: 2 }}/>
          Cumulative savings
        </span>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}>
          <span style={{ width: 14, borderTop: "1px dashed var(--fg-2)" }}/>
          Install cost
        </span>
      </div>
    </div>
  );
}

Object.assign(window, { SolarROI });
