/* ============================================================
   Homeowner mode — split screen
   ============================================================ */
/* global React, HomeMapView, Icon, LineChart20, BarChart */
const { useState: useStateH, useMemo: useMemoH, useEffect: useEffectH } = React;
const { INR, NUM, suryaGharSubsidy, simplePayback, npv, emi, co2Tonnes, treesEquivalent, carKmEquivalent, dieselSavings, annualProduction, systemKwFromPanels, CO2_PER_KWH } = window.LEPTON_UTILS;

const DEFAULT_LAYERS = {
  rgb: false,
  annualFlux: true,
  monthlyFlux: false,
  shaded: false,
  dsm: false,
  mask: false,
  segments: true,
  panels: true,
};

const LAYER_DEFS = [
  { id: "rgb",         label: "RGB orthophoto",     group: "imagery", swatch: "swatch-rgb",      kbd: "1" },
  { id: "mask",        label: "Building mask",      group: "imagery", swatch: "swatch-mask",     kbd: "2" },
  { id: "annualFlux",  label: "Annual flux",        group: "data",    swatch: "swatch-flux",     kbd: "3" },
  { id: "monthlyFlux", label: "Monthly flux",       group: "data",    swatch: "swatch-monthly",  kbd: "4" },
  { id: "shaded",      label: "Sun hours / yr",     group: "data",    swatch: "swatch-shade",    kbd: "5" },
  { id: "dsm",         label: "DSM (heightmap)",    group: "data",    swatch: "swatch-dsm",      kbd: "6" },
  { id: "segments",    label: "Roof segments",      group: "vector",  swatch: "swatch-segments", kbd: "7" },
  { id: "panels",      label: "Panel layout",       group: "vector",  swatch: "swatch-panels",   kbd: "8" },
];

function LayerRow({ def, on, onToggle }) {
  return (
    <div
      className={`layerrow ${on ? "is-active" : ""}`}
      onClick={() => onToggle(def.id)}
      style={{ gridTemplateColumns: "20px 14px 1fr auto" }}
    >
      <div
        title={on ? "Hide layer" : "Show layer"}
        style={{
          width: 20, height: 20, borderRadius: 4,
          display: "grid", placeItems: "center",
          color: on ? "var(--ink-1)" : "var(--ink-4)",
        }}
      >
        <Icon name={on ? "eye" : "eye-off"} size={13} color="currentColor"/>
      </div>
      <div className={`swatch ${def.swatch}`} style={{ width: 10, height: 10, borderRadius: 2, opacity: on ? 1 : 0.5 }}></div>
      <div className="lbl">{def.label}</div>
      <div className="kbd">{def.kbd}</div>
    </div>
  );
}

function LayerPanel({ layers, onToggle, building, monthIdx }) {
  const groups = [
    { label: "Imagery", filter: "imagery" },
    { label: "Solar API rasters", filter: "data" },
    { label: "Vector", filter: "vector" },
  ];
  const onCount = LAYER_DEFS.filter(l => layers[l.id]).length;
  return (
    <div className="layerpanel">
      <div className="layerpanel-head">
        <div className="row-flex" style={{ gap: 6 }}>
          <Icon name="layers" size={12} color="#57574f"/>
          <div className="t-label" style={{ color: "#0d0d0c" }}>Layers</div>
        </div>
        <div className="t-tag">{onCount} / {LAYER_DEFS.length}</div>
      </div>
      <div className="layerpanel-body">
        {groups.map(g => (
          <div key={g.filter} className="layerpanel-section">
            <div className="t-label">{g.label}</div>
            {LAYER_DEFS.filter(l => l.group === g.filter).map(l => (
              <LayerRow key={l.id} def={l} on={!!layers[l.id]} onToggle={onToggle}/>
            ))}
          </div>
        ))}
      </div>
      <div className="imagery-badge">
        <div className="row"><span className="k">imagery date</span><span className="v">{building.imageryDate}</span></div>
        <div className="row"><span className="k">quality</span><span className="v warn">{building.imageryQuality}</span></div>
      </div>
    </div>
  );
}

function MonthScrubber({ monthIdx, setMonthIdx, building, playing, setPlaying, visible }) {
  if (!visible) return null;
  const factors = building.monthFlux.map(m => m.factor);
  const maxF = Math.max(...factors);
  return (
    <div className="monthscrub">
      <button className="play" onClick={() => setPlaying(!playing)}>
        <Icon name={playing ? "pause" : "play"} size={12}/>
      </button>
      <div className="monthscrub-ticks">
        {building.monthFlux.map((m, i) => (
          <button key={i} className={i === monthIdx ? "is-active" : ""} onClick={() => setMonthIdx(i)}>
            <div className="bar" style={{ height: 4 + (m.factor / maxF) * 18 }}></div>
            {m.m}
          </button>
        ))}
      </div>
      <div className="label">
        {building.monthFlux[monthIdx].m}<br/>
        <span style={{ color: "var(--ink-1)" }}>×{building.monthFlux[monthIdx].factor.toFixed(2)}</span>
      </div>
    </div>
  );
}

function MapLegend({ activeLayers }) {
  // pick the primary "data" layer for the legend
  if (activeLayers.annualFlux) {
    return (
      <div className="maplegend">
        <div className="head">Annual flux</div>
        <div className="ramp"></div>
        <div className="axis"><span>500</span><span>1100</span><span>1750 kWh/m²</span></div>
      </div>
    );
  }
  if (activeLayers.monthlyFlux) {
    return (
      <div className="maplegend">
        <div className="head">Monthly flux</div>
        <div className="ramp" style={{ background: "linear-gradient(90deg, #1a1147, #ee6d3d, #fde725)" }}></div>
        <div className="axis"><span>low</span><span>high</span></div>
      </div>
    );
  }
  if (activeLayers.shaded) {
    return (
      <div className="maplegend">
        <div className="head">Sun hours / yr</div>
        <div className="ramp" style={{ background: "linear-gradient(90deg, #0c4a6e, #14b8a6, #facc15, #f97316)" }}></div>
        <div className="axis"><span>shaded</span><span>partial</span><span>full sun</span></div>
        <div style={{ marginTop: 6, fontSize: 10.5, color: "var(--ink-3)", fontFamily: "var(--font-mono)" }}>
          Σ over 12 × 24 hourly-shade bitmasks · max ≈ 4380 hrs (daylight half)
        </div>
      </div>
    );
  }
  if (activeLayers.dsm) {
    return (
      <div className="maplegend">
        <div className="head">DSM elevation</div>
        <div className="ramp" style={{ background: "linear-gradient(90deg, #0d3b66, #faf0ca, #f95738)" }}></div>
        <div className="axis"><span>210m</span><span>225m</span><span>240m</span></div>
      </div>
    );
  }
  if (activeLayers.segments && !activeLayers.annualFlux) {
    return (
      <div className="maplegend">
        <div className="head">Roof segments</div>
        <div className="row-list">
          {["#f59e0b","#3b82f6","#10b981","#ec4899"].map((c,i) => (
            <div className="row" key={i}><span className="sw" style={{background:c}}></span>S{i+1}</div>
          ))}
        </div>
      </div>
    );
  }
  return null;
}

/* ============================================================
   Side panel: Stats / Segments / System / Financials / Tweaks
   ============================================================ */
function StatsBlock({ building, systemKw, annualKwh }) {
  return (
    <div className="sp-section">
      <div className="sp-section-head">
        <div className="t-label">Roof potential</div>
      </div>
      <div className="sp-grid">
        <div className="sp-cell">
          <div className="k">Max array</div>
          <div className="v">{building.maxArrayPanelsCount}<span className="u">panels</span></div>
          <div className="delta">≈ {building.maxArrayAreaMeters2.toFixed(1)} m² usable</div>
        </div>
        <div className="sp-cell">
          <div className="k">Max system</div>
          <div className="v">{(building.maxArrayPanelsCount * building.panelCapacityWatts / 1000).toFixed(1)}<span className="u">kWp</span></div>
          <div className="delta">@ {building.panelCapacityWatts}W panel</div>
        </div>
        <div className="sp-cell">
          <div className="k">Max sunshine</div>
          <div className="v">{NUM(building.maxSunshineHoursPerYear)}<span className="u">hrs/yr</span></div>
          <div className="delta">25th–95th pctile across roof</div>
        </div>
        <div className="sp-cell">
          <div className="k">Annual production</div>
          <div className="v">{NUM(annualKwh)}<span className="u">kWh</span></div>
          <div className="delta pos">{systemKw} kWp · {Math.round(annualKwh/systemKw)} kWh/kWp/yr</div>
        </div>
      </div>
    </div>
  );
}

function SegmentTable({ building, hoveredSegment, onHoverSegment }) {
  const segColors = ["#f59e0b", "#3b82f6", "#10b981", "#ec4899"];
  return (
    <div className="sp-section">
      <div className="sp-section-head">
        <div className="t-label">Roof segments</div>
        <div className="t-tag">{building.roofSegments.length}</div>
      </div>
      {(() => {
        const totalKwh = building.roofSegments.reduce((a, s) => a + (s.yearlyKwhContribution || 0), 0);
        const bestSeg = totalKwh > 0
          ? building.roofSegments.reduce((a, b) => (b.yearlyKwhContribution || 0) > (a.yearlyKwhContribution || 0) ? b : a)
          : null;
        return (
          <>
            <table className="segtable">
              <thead>
                <tr>
                  <th>id</th><th>azimuth · pitch</th>
                  <th style={{ textAlign: "right" }}>panels</th>
                  <th style={{ textAlign: "right" }}>kWh/yr</th>
                  <th style={{ textAlign: "right" }}>sun h/yr</th>
                </tr>
              </thead>
              <tbody>
                {building.roofSegments.map((seg, idx) => {
                  const isBest = bestSeg && seg.id === bestSeg.id && totalKwh > 0;
                  const sharePct = totalKwh > 0 ? Math.round((seg.yearlyKwhContribution || 0) / totalKwh * 100) : 0;
                  return (
                    <tr
                      key={seg.id}
                      className={hoveredSegment === seg.id ? "is-hover" : ""}
                      onMouseEnter={() => onHoverSegment(seg.id)}
                      onMouseLeave={() => onHoverSegment(null)}
                    >
                      <td className="lead">
                        <span className="seg-dot" style={{ background: segColors[idx % 4] }}></span>
                        {seg.id}
                        {isBest && <span className="tag pos" style={{ marginLeft: 6, padding: "1px 5px", fontSize: 9 }}>BEST</span>}
                      </td>
                      <td>{seg.azimuthDeg}° / {seg.pitchDeg}°</td>
                      <td style={{ textAlign: "right" }}>{seg.panelsAllocated || 0}</td>
                      <td style={{ textAlign: "right" }}>
                        {NUM(seg.yearlyKwhContribution || 0)}
                        {sharePct > 0 && <span style={{ color: "var(--ink-3)", marginLeft: 4 }}>{sharePct}%</span>}
                      </td>
                      <td style={{ textAlign: "right" }}>{NUM(seg.sunshineHours)}</td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
            {building.wholeRoofSunshineQuantiles && building.wholeRoofSunshineQuantiles.length >= 11 && (
              <div style={{ marginTop: 10 }}>
                <div className="t-tiny" style={{ marginBottom: 4 }}>
                  Roof sunshine distribution
                </div>
                <div style={{ display: "flex", gap: 1, alignItems: "flex-end", height: 28 }}>
                  {building.wholeRoofSunshineQuantiles.map((q, i) => {
                    const max = Math.max(...building.wholeRoofSunshineQuantiles);
                    const h = max > 0 ? (q / max) * 100 : 0;
                    const labels = ["0%", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100%"];
                    return (
                      <div key={i} title={`${labels[i]}: ${NUM(q)} h/yr`}
                        style={{
                          flex: 1, height: `${h}%`,
                          background: i === 5 ? "var(--accent-strong)" : "var(--ink-5)",
                          borderRadius: "2px 2px 0 0",
                        }}
                      ></div>
                    );
                  })}
                </div>
                <div className="row-flex" style={{ justifyContent: "space-between", fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--ink-3)", marginTop: 4 }}>
                  <span>worst {NUM(building.wholeRoofSunshineQuantiles[0])} h</span>
                  <span>median {NUM(building.wholeRoofSunshineQuantiles[5])} h</span>
                  <span>best {NUM(building.wholeRoofSunshineQuantiles[10])} h</span>
                </div>
              </div>
            )}
          </>
        );
      })()}
    </div>
  );
}

function SystemSlider({ panelCount, setPanelCount, building, systemKw, annualKwh }) {
  return (
    <div className="sp-section">
      <div className="sp-section-head">
        <div className="t-label">System size</div>
        <div className="tag accent">{systemKw} kWp</div>
      </div>
      <div className="field">
        <div className="field-row">
          <span className="lab">Panel count</span>
          <span className="val">{panelCount} <span style={{ color: "var(--ink-3)" }}>/ {building.maxArrayPanelsCount}</span></span>
        </div>
        <input type="range" className="slider"
          min="4" max={building.maxArrayPanelsCount} step="1"
          value={panelCount}
          onChange={e => setPanelCount(+e.target.value)} />
        <div className="row-flex" style={{ justifyContent: "space-between", fontFamily: "var(--font-mono)", fontSize: 10.5, color: "var(--ink-3)" }}>
          <span>min 4</span>
          <span>{Math.round(annualKwh / 12)} kWh / month avg</span>
          <span>max {building.maxArrayPanelsCount}</span>
        </div>
      </div>
    </div>
  );
}

function TweaksBlock({ tweaks, setTweaks, discoms, monthlyBill, setMonthlyBill }) {
  const T = tweaks;
  const update = (k, v) => setTweaks({ ...T, [k]: v });
  return (
    <div className="sp-section">
      <div className="sp-section-head">
        <div className="t-label">Custom tweaks</div>
        <div className="tag" style={{ background: "transparent", borderColor: "var(--line)" }}>India-specific</div>
      </div>

      {/* Energy profile: DISCOM, bill or units, peak bill, sanctioned load */}
      <div className="tweak-group">
        <div className="tweak-head">
          <div className="ti">
            <Icon name="currency" size={13} color="#57574f"/>
            Your electricity
          </div>
          <div className="tag on">{discoms.find(d => d.id === T.discomId)?.name}</div>
        </div>
        <div className="tweak-body">
          {(() => {
            const discom = discoms.find(d => d.id === T.discomId);
            const tariff = discom?.tariff || 7;
            const monthlyKwh = Math.round(monthlyBill / tariff);
            return (
              <>
                <div className="field">
                  <div className="field-row"><span className="lab">DISCOM</span><span className="val">{tariff.toFixed(2)} ₹/kWh</span></div>
                  <select className="select" value={T.discomId} onChange={e => update("discomId", e.target.value)}>
                    {discoms.map(d => <option key={d.id} value={d.id}>{d.name} · {d.region}</option>)}
                  </select>
                </div>

                {/* Bill ↔ Units toggle */}
                <div className="field">
                  <div className="field-row">
                    <span className="lab">{T.billUnit === "inr" ? "Monthly bill" : "Monthly consumption"}</span>
                    <div className="seg">
                      <button className={T.billUnit === "inr" ? "is-active" : ""} onClick={() => update("billUnit", "inr")}>₹</button>
                      <button className={T.billUnit === "kwh" ? "is-active" : ""} onClick={() => update("billUnit", "kwh")}>kWh</button>
                    </div>
                  </div>
                  {T.billUnit === "inr" ? (
                    <div style={{ position: "relative", marginTop: 4 }}>
                      <span style={{ position: "absolute", left: 10, top: "50%", transform: "translateY(-50%)", color: "var(--ink-3)", fontFamily: "var(--font-mono)", fontSize: 12 }}>₹</span>
                      <input
                        type="number" className="numinput" min="0" step="100"
                        value={monthlyBill}
                        onChange={e => setMonthlyBill(Math.max(0, +e.target.value || 0))}
                        style={{ paddingLeft: 22 }}
                      />
                    </div>
                  ) : (
                    <div style={{ position: "relative", marginTop: 4 }}>
                      <input
                        type="number" className="numinput" min="0" step="10"
                        value={monthlyKwh}
                        onChange={e => setMonthlyBill(Math.round(Math.max(0, +e.target.value || 0) * tariff))}
                        style={{ paddingRight: 36 }}
                      />
                      <span style={{ position: "absolute", right: 10, top: "50%", transform: "translateY(-50%)", color: "var(--ink-3)", fontFamily: "var(--font-mono)", fontSize: 11 }}>kWh</span>
                    </div>
                  )}
                  <div className="row-flex" style={{ justifyContent: "space-between", fontFamily: "var(--font-mono)", fontSize: 10.5, color: "var(--ink-3)", marginTop: 6 }}>
                    <span>{INR(monthlyBill)} / mo  ·  {NUM(monthlyKwh)} kWh / mo</span>
                    <span>{NUM(monthlyKwh * 12)} kWh / yr</span>
                  </div>
                </div>

                {/* Peak (summer) bill — optional */}
                <div className="field">
                  <div className="field-row">
                    <span className="lab">Peak summer bill <span className="muted">(optional)</span></span>
                  </div>
                  <div style={{ position: "relative" }}>
                    <span style={{ position: "absolute", left: 10, top: "50%", transform: "translateY(-50%)", color: "var(--ink-3)", fontFamily: "var(--font-mono)", fontSize: 12 }}>₹</span>
                    <input
                      type="number" className="numinput" min="0" step="100"
                      value={T.peakBill || ""}
                      placeholder="0"
                      onChange={e => update("peakBill", Math.max(0, +e.target.value || 0))}
                      style={{ paddingLeft: 22 }}
                    />
                  </div>
                  <div className="t-small">
                    {T.peakBill > 0
                      ? `Peak ≈ ${(T.peakBill / monthlyBill).toFixed(1)}× average. We weight 3 peak months into annual usage.`
                      : "Leave blank if average bill is fine. Most Indian homes peak in May–Jul on AC."}
                  </div>
                </div>

                {/* Sanctioned load — optional */}
                <div className="field">
                  <div className="field-row">
                    <span className="lab">Sanctioned load <span className="muted">(from DISCOM bill)</span></span>
                  </div>
                  <div style={{ position: "relative" }}>
                    <input
                      type="number" className="numinput" min="0" step="0.5"
                      value={T.sanctionedLoadKw || ""}
                      placeholder="0"
                      onChange={e => update("sanctionedLoadKw", Math.max(0, +e.target.value || 0))}
                      style={{ paddingRight: 32 }}
                    />
                    <span style={{ position: "absolute", right: 10, top: "50%", transform: "translateY(-50%)", color: "var(--ink-3)", fontFamily: "var(--font-mono)", fontSize: 11 }}>kW</span>
                  </div>
                  <div className="t-small">
                    Net-metering is capped at sanctioned load in most states. Leave blank if unsure.
                  </div>
                </div>
              </>
            );
          })()}
        </div>
      </div>

      {/* EV charging plan */}
      <div className="tweak-group">
        <div className="tweak-head">
          <div className="ti">
            <Icon name="car" size={13} color="#57574f"/>
            EV charging plan
          </div>
          <div className={`tag ${T.evEnabled ? "on" : ""}`}>{T.evEnabled ? `${T.evKmPerDay} km/d` : "off"}</div>
        </div>
        <div className="tweak-body">
          <label
            className={`toggle ${T.evEnabled ? "is-on" : ""}`}
            style={{ marginBottom: 8, cursor: "pointer" }}
            onClick={() => update("evEnabled", !T.evEnabled)}
          >
            <span className="toggle-switch"></span>
            <span className="lab">Plan to charge an EV at home</span>
          </label>
          {T.evEnabled && (
            <>
              <div className="field">
                <div className="field-row"><span className="lab">Distance / day</span><span className="val">{T.evKmPerDay} km</span></div>
                <input type="range" className="slider" min="5" max="120" step="5" value={T.evKmPerDay}
                  onChange={e => update("evKmPerDay", +e.target.value)} />
                <div className="t-small">
                  Adds ≈ {NUM(Math.round(T.evKmPerDay * 365 * 0.15))} kWh / yr to your load
                  ({Math.round(T.evKmPerDay * 0.15 * 30)} kWh / mo · ~ ₹{NUM(Math.round(T.evKmPerDay * 365 * 0.15 * (discoms.find(d=>d.id===T.discomId)?.tariff || 7)))} / yr at grid rate).
                  Solar offsets this entirely if sized right.
                </div>
              </div>
            </>
          )}
        </div>
      </div>

      {/* Flat-roof tilt */}
      <div className="tweak-group">
        <div className="tweak-head">
          <div className="ti">
            <Icon name="tilt" size={13} color="#57574f"/>
            Flat-roof tilt override
          </div>
          <div className={`tag ${T.tiltEnabled ? "on" : ""}`}>{T.tiltEnabled ? `${T.tiltDeg}°` : "off"}</div>
        </div>
        <div className="tweak-body">
          <label
            className={`toggle ${T.tiltEnabled ? "is-on" : ""}`}
            style={{ marginBottom: 8, cursor: "pointer" }}
            onClick={() => update("tiltEnabled", !T.tiltEnabled)}
          >
            <span className="toggle-switch"></span>
            <span className="lab">Mount terrace (S4) panels on tilted frames</span>
          </label>
          {T.tiltEnabled && (
            <div className="field">
              <div className="field-row"><span className="lab">Tilt angle</span><span className="val">{T.tiltDeg}°</span></div>
              <input type="range" className="slider" min="5" max="30" step="1" value={T.tiltDeg} onChange={e => update("tiltDeg", +e.target.value)} />
              <div className="t-small">Lat-optimal ≈ 24° in Gurugram. +{Math.round((1 - Math.abs(T.tiltDeg - 24) / 24) * 18)}% on flat segment.</div>
            </div>
          )}
        </div>
      </div>

      {/* Battery */}
      <div className="tweak-group">
        <div className="tweak-head">
          <div className="ti">
            <Icon name="battery" size={13} color="#57574f"/>
            Battery add-on
          </div>
          <div className={`tag ${T.batteryKwh > 0 ? "on" : ""}`}>{T.batteryKwh > 0 ? `${T.batteryKwh} kWh` : "none"}</div>
        </div>
        <div className="tweak-body">
          <div className="field">
            <div className="field-row"><span className="lab">Capacity</span><span className="val">{T.batteryKwh} kWh</span></div>
            <input type="range" className="slider" min="0" max="15" step="1" value={T.batteryKwh} onChange={e => update("batteryKwh", +e.target.value)} />
            <div className="t-small">+₹{NUM(T.batteryKwh * 32000)} CAPEX · {Math.min(95, 35 + T.batteryKwh * 4)}% self-consumption.</div>
          </div>
        </div>
      </div>

      {/* Diesel offset */}
      <div className="tweak-group">
        <div className="tweak-head">
          <div className="ti">
            <Icon name="drum" size={13} color="#57574f"/>
            Diesel offset mode
          </div>
          <div className={`tag ${T.dieselEnabled ? "on" : ""}`}>{T.dieselEnabled ? `${T.dieselHrs} h/d` : "off"}</div>
        </div>
        <div className="tweak-body">
          <label
            className={`toggle ${T.dieselEnabled ? "is-on" : ""}`}
            style={{ marginBottom: 8, cursor: "pointer" }}
            onClick={() => update("dieselEnabled", !T.dieselEnabled)}
          >
            <span className="toggle-switch"></span>
            <span className="lab">Compare payback vs. diesel genset</span>
          </label>
          {T.dieselEnabled && (
            <>
              <div className="field">
                <div className="field-row"><span className="lab">Diesel price</span><span className="val">₹{T.dieselPrice} / L</span></div>
                <input type="range" className="slider" min="85" max="120" step="1" value={T.dieselPrice} onChange={e => update("dieselPrice", +e.target.value)} />
              </div>
              <div className="field">
                <div className="field-row"><span className="lab">Genset hrs / day</span><span className="val">{T.dieselHrs} h</span></div>
                <input type="range" className="slider" min="0" max="12" step="0.5" value={T.dieselHrs} onChange={e => update("dieselHrs", +e.target.value)} />
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

function FinancialsBlock({ building, systemKw, annualKwh, tariff, tweaks, monthlyBill, discom }) {
  // CAPEX
  const baseCapex = Math.round(systemKw * 62000);
  const batteryCapex = tweaks.batteryKwh * 32000;
  const totalCapex = baseCapex + batteryCapex;

  // Subsidy
  const subRes = suryaGharSubsidy(systemKw);
  const netCapex = totalCapex - subRes.subsidy;

  // Annual baseline consumption (kWh).
  // If user provided a peak summer bill, weight 3 peak months at peak ₹ + 9 months at avg.
  // EV adds extra load if user planned for it.
  const effectiveAnnualBill = tweaks.peakBill > 0
    ? tweaks.peakBill * 3 + monthlyBill * 9
    : monthlyBill * 12;
  const evKwh = tweaks.evEnabled ? Math.round(tweaks.evKmPerDay * 365 * 0.15) : 0;
  const annualUsageKwh = Math.round(effectiveAnnualBill / tariff) + evKwh;

  // Savings — capped by usage
  const exported = Math.max(0, annualKwh - annualUsageKwh);
  const selfConsumed = annualKwh - exported;
  // self-consumed @ tariff, exported @ feed-in (₹2/kWh net metering avg)
  const exportRate = 2.0;
  const annualSavings = Math.round(selfConsumed * tariff + exported * exportRate);

  // CO2 — use Solar API's building-specific carbon factor when available
  // (CEA's grid factor varies by region; API reports ~0.93 kg/kWh for North India,
  // vs our generic 0.82 default).
  const co2KgPerKwh = (building?.carbonOffsetKgPerKwh && building.carbonOffsetKgPerKwh > 0)
    ? building.carbonOffsetKgPerKwh
    : CO2_PER_KWH;
  const annualCo2Kg = Math.round(annualKwh * co2KgPerKwh);

  // Lifetime — Solar API tells us panelLifetimeYears (typically 20).
  const lifetimeYears = building?.panelLifetimeYears || 20;

  // Payback / NPV — use the API-provided lifetime.
  const paybackYears = simplePayback(netCapex, annualSavings);
  const npv20 = npv(netCapex, annualSavings, lifetimeYears, 0.08, 0.04);

  // EMI (SBI Surya Ghar): 6.75%, 10y
  const emiAmount = Math.round(emi(netCapex, 0.0675, 10));

  // Diesel
  const dieselSav = tweaks.dieselEnabled
    ? Math.round(annualKwh * 0.28 * (tweaks.dieselHrs / 8) * tweaks.dieselPrice * 0.6)
    : 0;
  const dieselPayback = tweaks.dieselEnabled && dieselSav > 0 ? +(netCapex / (annualSavings + dieselSav)).toFixed(1) : null;

  // Lifetime curve — Solar API tells us panelLifetimeYears (typically 20)
  const escalation = 0.04;
  const withSolar = [];
  const withoutSolar = [];
  {
    let solarCum = -netCapex;
    let nonCum = 0;
    let s = annualSavings;
    let g = annualUsageKwh * tariff;
    for (let y = 0; y < lifetimeYears; y++) {
      solarCum += s;
      nonCum -= g;
      withSolar.push(Math.round(solarCum));
      withoutSolar.push(Math.round(nonCum));
      s *= 1 + escalation;
      g *= 1 + escalation;
    }
  }
  const breakEvenYear = withSolar.findIndex(v => v >= 0) + 1;

  return (
    <div className="sp-section">
      <div className="sp-section-head">
        <div className="t-label">Financials · India math</div>
        <div className="tag accent">PM Surya Ghar</div>
      </div>

      <div className="fin-headline">
        <div>
          <div className="k">Net payback</div>
          <div className="v">{paybackYears < 100 ? paybackYears.toFixed(1) : "—"}<span className="u">years</span></div>
        </div>
        <div className="right">
          <div className="k">NPV @ 8% · {lifetimeYears}y</div>
          <div className="v">{INR(npv20)}</div>
        </div>
      </div>

      <div className="fin-list">
        <div className="l">System CAPEX <span className="muted">({systemKw} kWp @ ₹62k/kWp)</span></div>
        <div className="r">{INR(baseCapex)}</div>
        {tweaks.batteryKwh > 0 && <>
          <div className="l">Battery <span className="muted">({tweaks.batteryKwh} kWh)</span></div>
          <div className="r">+ {INR(batteryCapex)}</div>
        </>}
        <div className="l">PM Surya Ghar subsidy <span className="asterisk">*</span></div>
        <div className="r" style={{ color: "var(--pos)" }}>− {INR(subRes.subsidy)}</div>
        <div className="total-l">Net upfront</div>
        <div className="total-r">{INR(netCapex)}</div>
      </div>

      {/* Sanctioned-load + EV usage callouts */}
      {(tweaks.sanctionedLoadKw > 0 || tweaks.evEnabled) && (
        <div style={{ marginTop: 10, display: "grid", gap: 6 }}>
          {tweaks.sanctionedLoadKw > 0 && systemKw > tweaks.sanctionedLoadKw && (
            <div className="t-tiny" style={{ padding: "6px 10px", borderRadius: 5, background: "var(--neg-soft)", color: "var(--neg)" }}>
              <Icon name="info" size={10} color="currentColor"/> System ({systemKw} kWp) exceeds your {tweaks.sanctionedLoadKw} kW sanctioned load. Most DISCOMs cap net-metering at sanctioned load — you'd need a load enhancement first.
            </div>
          )}
          {tweaks.evEnabled && (
            <div className="t-tiny" style={{ padding: "6px 10px", borderRadius: 5, background: "var(--bg-sunken)", color: "var(--ink-2)" }}>
              <Icon name="car" size={10} color="currentColor"/> EV load: {NUM(evKwh)} kWh / yr included in consumption ({Math.round(evKwh / annualKwh * 100)}% of solar output goes to the EV).
            </div>
          )}
        </div>
      )}

      {/* Subsidy bar */}
      <div style={{ marginTop: 12 }}>
        <div className="subsidy-bar">
          <div className="seg-sub" style={{ width: `${(subRes.subsidy / totalCapex) * 100}%` }}></div>
          <div className="seg-self" style={{ flex: 1 }}></div>
        </div>
        <div className="subsidy-legend">
          <span><span className="dot" style={{background: "var(--accent)"}}></span>Subsidized {INR(subRes.subsidy)} ({((subRes.subsidy/totalCapex)*100).toFixed(0)}%)</span>
          <span><span className="dot" style={{background: "var(--ink-2)"}}></span>Self-funded {INR(netCapex)}</span>
        </div>
        <div className="t-tiny" style={{ marginTop: 6, color: "var(--accent-strong)" }}>
          <Icon name="info" size={10} color="currentColor"/> *Residential only · empanelled vendor required · capped at 3 kW (₹78,000)
        </div>
      </div>

      <div className="hr"></div>

      {/* Annual savings + CO2 */}
      <div className="sp-grid">
        <div className="sp-cell">
          <div className="k">Annual savings</div>
          <div className="v">{INR(annualSavings)}</div>
          <div className="delta">
            self-cons {NUM(selfConsumed)} · export {NUM(exported)} kWh
          </div>
        </div>
        <div className="sp-cell">
          <div className="k">CO₂ offset</div>
          <div className="v">{(annualCo2Kg / 1000).toFixed(2)}<span className="u">t/yr</span></div>
          <div className="delta">≡ {NUM(treesEquivalent(annualCo2Kg))} trees · {NUM(carKmEquivalent(annualCo2Kg))} car-km</div>
        </div>
      </div>

      {/* Lifetime curve (panelLifetimeYears from Solar API) */}
      <div style={{ marginTop: 14 }}>
        <div className="sp-section-head" style={{ marginBottom: 4 }}>
          <div className="t-label">{lifetimeYears}-year cumulative</div>
          <div className="t-tag">tariff esc 4%/yr</div>
        </div>
        <LineChart20 years={lifetimeYears} withSolar={withSolar} withoutSolar={withoutSolar} breakEvenYear={breakEvenYear} />
      </div>

      <div className="hr"></div>

      {/* SBI Surya Ghar EMI */}
      <div>
        <div className="sp-section-head" style={{ marginBottom: 8 }}>
          <div className="t-label">SBI Surya Ghar loan</div>
          <div className="t-tag">6.75% · 10 yr</div>
        </div>
        <div className="fin-list">
          <div className="l">Principal</div><div className="r">{INR(netCapex)}</div>
          <div className="l">Monthly EMI</div><div className="r" style={{ color: "var(--accent-strong)" }}>{INR(emiAmount)}</div>
          <div className="l">vs. monthly bill saved</div>
          <div className="r" style={{ color: "var(--pos)" }}>−{INR(Math.round(annualSavings/12))}</div>
          <div className="total-l">Net monthly outlay</div>
          <div className="total-r" style={{ color: emiAmount - annualSavings/12 < 0 ? "var(--pos)" : "var(--ink-1)" }}>
            {INR(emiAmount - Math.round(annualSavings/12))}
          </div>
        </div>
      </div>

      {/* Diesel mode */}
      {tweaks.dieselEnabled && (
        <>
          <div className="hr"></div>
          <div>
            <div className="sp-section-head" style={{ marginBottom: 8 }}>
              <div className="t-label">Diesel offset · alternative payback</div>
              <div className="t-tag">{tweaks.dieselHrs} hrs/d @ ₹{tweaks.dieselPrice}/L</div>
            </div>
            <div className="fin-list">
              <div className="l">Diesel saved per year</div>
              <div className="r">{INR(dieselSav)}</div>
              <div className="l">Combined annual savings</div>
              <div className="r">{INR(annualSavings + dieselSav)}</div>
              <div className="total-l">Diesel-adjusted payback</div>
              <div className="total-r" style={{ color: "var(--pos)" }}>{dieselPayback} years</div>
            </div>
          </div>
        </>
      )}
    </div>
  );
}

/* ============================================================
   Main HomeownerMode
   ============================================================ */
function HomeownerMode() {
  const data = window.useLeptonData();
  const HOME_BUILDING = data.HOME_BUILDING;
  const DISCOMS = data.DISCOMS;
  const [layers, setLayers] = useStateH(DEFAULT_LAYERS);
  const [monthIdx, setMonthIdx] = useStateH(3); // April
  const [playing, setPlaying] = useStateH(false);
  const [panelCount, setPanelCount] = useStateH(28);
  const [hoveredSegment, setHoveredSegment] = useStateH(null);
  const [monthlyBill, setMonthlyBill] = useStateH(4200);
  const [tweaks, setTweaks] = useStateH({
    discomId: "dhbvn",
    // Energy profile
    billUnit: "inr",           // 'inr' | 'kwh' — drives which slider is shown
    peakBill: 0,               // 0 = not set; if set, used for summer-aware sizing
    sanctionedLoadKw: 0,       // 0 = not set; warns if proposed system exceeds
    // Roof + add-ons
    tiltEnabled: true,
    tiltDeg: 20,
    batteryKwh: 0,
    // Future load
    evEnabled: false,
    evKmPerDay: 30,
    // Backup
    dieselEnabled: false,
    dieselPrice: 95,
    dieselHrs: 3,
  });

  // play month animation
  useEffectH(() => {
    if (!playing) return;
    const t = setInterval(() => setMonthIdx(m => (m + 1) % 12), 700);
    return () => clearInterval(t);
  }, [playing]);

  // keyboard shortcuts for layers
  useEffectH(() => {
    const handler = (e) => {
      if (e.target.tagName === "INPUT" || e.target.tagName === "SELECT") return;
      const def = LAYER_DEFS.find(l => l.kbd === e.key);
      if (def) {
        setLayers(L => ({ ...L, [def.id]: !L[def.id] }));
      }
    };
    window.addEventListener("keydown", handler);
    return () => window.removeEventListener("keydown", handler);
  }, []);

  const toggleLayer = (id) => setLayers(L => ({ ...L, [id]: !L[id] }));

  if (!HOME_BUILDING) {
    return <LoadingScreen label={data.loading.home ? "Fetching Solar API data…" : (data.error.home || "Initializing…")} error={data.error.home}/>;
  }

  const systemKw = systemKwFromPanels(panelCount, HOME_BUILDING.panelCapacityWatts);
  const annualKwh = annualProduction({
    building: HOME_BUILDING,
    panels: panelCount,
    tiltOverride: tweaks.tiltEnabled ? tweaks.tiltDeg : null,
  });

  const discom = DISCOMS.find(d => d.id === tweaks.discomId);

  const pendingLocation = data.pendingLocation;
  const pendingPolygon = data.pendingPolygon;
  const selectionMode = data.selectionMode;
  const lastSelection = data.lastSelection;
  const isComputing = data.loading.home;

  return (
    <div className="split">
      {/* MAP */}
      <div className="split-map">
        <HomeMapView
          building={HOME_BUILDING}
          activeLayers={layers}
          monthIdx={monthIdx}
          panelCount={panelCount}
          hoveredSegment={hoveredSegment}
          onHoverSegment={setHoveredSegment}
          pendingLocation={pendingLocation}
          pendingPolygon={pendingPolygon}
          selectionMode={selectionMode}
          lastSelection={lastSelection}
        />
        <AddrBar building={HOME_BUILDING}/>
        <PolygonToggle selectionMode={selectionMode}/>
        <LayerPanel layers={layers} onToggle={toggleLayer} building={HOME_BUILDING} monthIdx={monthIdx}/>
        <MapLegend activeLayers={layers} />
        <MonthScrubber
          monthIdx={monthIdx}
          setMonthIdx={setMonthIdx}
          building={HOME_BUILDING}
          playing={playing}
          setPlaying={setPlaying}
          visible={layers.monthlyFlux}
        />
        {pendingLocation && (
          <LocationPanel
            pending={pendingLocation}
            polygon={pendingPolygon}
            isLoading={isComputing}
          />
        )}
        {!pendingLocation && lastSelection && lastSelection.offsetMeters >= 15 && (
          <AlignmentBanner offsetMeters={lastSelection.offsetMeters} />
        )}
      </div>
      {/* SIDE PANEL */}
      <div className="split-panel">
        <StatsBlock building={HOME_BUILDING} systemKw={systemKw} annualKwh={annualKwh} />
        <SegmentTable building={HOME_BUILDING} hoveredSegment={hoveredSegment} onHoverSegment={setHoveredSegment}/>
        <SystemSlider panelCount={panelCount} setPanelCount={setPanelCount} building={HOME_BUILDING} systemKw={systemKw} annualKwh={annualKwh}/>
        <TweaksBlock tweaks={tweaks} setTweaks={setTweaks} discoms={DISCOMS} monthlyBill={monthlyBill} setMonthlyBill={setMonthlyBill}/>
        <FinancialsBlock
          building={HOME_BUILDING}
          systemKw={systemKw}
          annualKwh={annualKwh}
          tariff={discom.tariff}
          tweaks={tweaks}
          monthlyBill={monthlyBill}
          discom={discom}
        />
      </div>
    </div>
  );
}

function AlignmentBanner({ offsetMeters }) {
  return (
    <div style={{
      position: "absolute", left: 268, top: 62, zIndex: 1000,
      background: "var(--bg-elev)", border: "1px solid #ef4444",
      borderRadius: 7, padding: "6px 10px",
      boxShadow: "0 2px 8px rgba(0,0,0,0.06)",
      display: "flex", alignItems: "center", gap: 8,
      maxWidth: 480,
    }}>
      <div style={{
        width: 8, height: 8, borderRadius: "50%", background: "#ef4444", flexShrink: 0,
      }}></div>
      <div className="t-small" style={{ color: "var(--ink-2)" }}>
        Solar API resolved a building <b>{Math.round(offsetMeters)} m</b> from your selection (the red dot on the map).
        Click closer to the rooftop or drag the pin to recompute.
      </div>
    </div>
  );
}

function LocationPanel({ pending, polygon, isLoading }) {
  const onCompute = () => {
    window.LEPTON_LOAD.commitPending();
  };
  const onCancel = () => {
    window.LEPTON_LOAD.clearPending();
  };
  return (
    <div style={{
      position: "absolute", left: 268, bottom: 14, zIndex: 1000,
      width: 360,
      background: "var(--bg-elev)", border: "1px solid var(--line-strong)",
      borderRadius: 8, boxShadow: "0 8px 24px rgba(0,0,0,0.10)",
      padding: 12,
    }}>
      <div className="t-label" style={{ marginBottom: 8, display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <span>{polygon ? "Drawn polygon" : "Pending location"}</span>
        <span className="t-tag" style={{ background: "var(--bg-sunken)" }}>{pending.source}</span>
      </div>
      {pending.label && (
        <div style={{ fontSize: 12.5, color: "var(--ink-1)", marginBottom: 4, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
          {pending.label}
        </div>
      )}
      <div className="t-mono" style={{ color: "var(--ink-3)", marginBottom: 10 }}>
        {pending.lat.toFixed(5)}°N · {pending.lng.toFixed(5)}°E
        {polygon && <span> · {polygon.length} pts</span>}
      </div>
      <div style={{ display: "flex", gap: 6 }}>
        <button
          className="btn primary"
          onClick={onCompute}
          disabled={isLoading}
          style={{ flex: 1, justifyContent: "center", opacity: isLoading ? 0.7 : 1 }}
        >
          {isLoading ? (
            <>
              <span style={{
                display: "inline-block", width: 10, height: 10, borderRadius: "50%",
                border: "1.5px solid white", borderTopColor: "transparent",
                animation: "lpspin 0.8s linear infinite",
              }} />
              Computing solar potential…
            </>
          ) : (
            <>
              <Icon name="sun" size={12} color="currentColor"/>
              Compute solar potential
            </>
          )}
        </button>
        <button className="btn" onClick={onCancel} disabled={isLoading}>
          <Icon name="x" size={11} color="currentColor"/>
        </button>
      </div>
    </div>
  );
}

function LoadingScreen({ label, error }) {
  return (
    <div style={{
      position: "absolute", inset: 0, display: "grid", placeItems: "center",
      background: "var(--bg)",
    }}>
      <div style={{ textAlign: "center", maxWidth: 380 }}>
        <div style={{
          width: 32, height: 32, borderRadius: 8, background: "var(--ink-1)",
          color: "var(--accent)", margin: "0 auto 14px",
          display: "grid", placeItems: "center",
          fontFamily: "var(--font-mono)", fontWeight: 600,
        }}>L</div>
        <div className="t-h2" style={{ marginBottom: 4 }}>Lepton Solar</div>
        <div className="t-small">{label || "Loading…"}</div>
        {error && (
          <div className="t-tiny" style={{ marginTop: 14, padding: "8px 12px", borderRadius: 6, background: "var(--neg-soft)", color: "var(--neg)" }}>
            {error}
          </div>
        )}
      </div>
    </div>
  );
}


// Place-type → icon. Mirrors how Google Maps differentiates suggestion rows.
function iconForPlaceTypes(types = []) {
  const t = new Set(types);
  if (t.has("establishment") || t.has("point_of_interest") || t.has("store") || t.has("hospital") || t.has("school")) return "warehouse";
  if (t.has("premise") || t.has("subpremise") || t.has("street_address") || t.has("route")) return "home";
  if (t.has("locality") || t.has("sublocality") || t.has("sublocality_level_1") || t.has("neighborhood")) return "people";
  if (t.has("administrative_area_level_1") || t.has("administrative_area_level_2") || t.has("country")) return "compass";
  return "pin";
}

// Detect a raw "lat, lng" (or "lat lng" / "lat;lng") in the search input.
// Accepts signed decimals; validates lat ∈ [-90, 90] and lng ∈ [-180, 180].
const LATLNG_RE = /^\s*(-?\d{1,2}(?:\.\d+)?)\s*[,\s;]\s*(-?\d{1,3}(?:\.\d+)?)\s*$/;
function parseLatLng(s) {
  const m = LATLNG_RE.exec(s);
  if (!m) return null;
  const lat = parseFloat(m[1]);
  const lng = parseFloat(m[2]);
  if (!Number.isFinite(lat) || !Number.isFinite(lng)) return null;
  if (lat < -90 || lat > 90 || lng < -180 || lng > 180) return null;
  return { lat, lng };
}

function AddrBar({ building, placeholder: placeholderProp, skipSetPending, defaultZoom = 18 }) {
  const inputRef = React.useRef(null);
  const [query, setQuery] = React.useState("");
  const [open, setOpen] = React.useState(false);
  const [suggestions, setSuggestions] = React.useState([]);
  const [highlight, setHighlight] = React.useState(0);
  const [focused, setFocused] = React.useState(false);

  // Building is optional (city mode has no current building).
  const placeholder = placeholderProp || (building && building.addressShort) || "Search place or lat, lng";

  const fetchSuggestions = async (v) => {
    if (v.length < 2) { setSuggestions([]); setOpen(false); return; }
    // If the input parses as raw lat,lng, surface a synthetic suggestion ABOVE
    // the place results — lets the user jump straight to coordinates.
    const ll = parseLatLng(v);
    const synthetic = ll ? [{
      synthetic: true,
      place_id: `_ll_${ll.lat}_${ll.lng}`,
      lat: ll.lat, lng: ll.lng,
      main: `${ll.lat.toFixed(5)}°, ${ll.lng.toFixed(5)}°`,
      secondary: "Jump to coordinates",
      description: `${ll.lat.toFixed(5)}, ${ll.lng.toFixed(5)}`,
      types: ["_latlng"],
    }] : [];
    try {
      const r = await fetch(`/api/places/autocomplete?q=${encodeURIComponent(v)}`);
      const j = await r.json();
      const preds = (j.predictions || []).slice(0, 6).map(p => ({
        place_id: p.place_id,
        main: p.structured_formatting?.main_text || p.description,
        secondary: p.structured_formatting?.secondary_text || "",
        description: p.description,
        types: p.types || [],
      }));
      setSuggestions([...synthetic, ...preds]);
      setOpen(true);
      setHighlight(0);
    } catch (e) {
      // If autocomplete fails (e.g. quota), still show the synthetic latlng row.
      if (synthetic.length) {
        setSuggestions(synthetic);
        setOpen(true);
        setHighlight(0);
      } else {
        console.error(e);
      }
    }
  };

  const onChange = (e) => {
    const v = e.target.value;
    setQuery(v);
    fetchSuggestions(v);
  };

  const clear = () => {
    setQuery("");
    setSuggestions([]);
    setOpen(false);
    inputRef.current?.focus();
  };

  const panAndMaybePin = (lat, lng, label, types) => {
    const zoom =
      types.includes("street_address") || types.includes("premise") || types.includes("subpremise") || types.includes("establishment") ? 20 :
      types.includes("sublocality") || types.includes("neighborhood") || types.includes("sublocality_level_1") ? 18 :
      types.includes("locality") || types.includes("administrative_area_level_3") ? 17 :
      types.includes("administrative_area_level_2") ? 15 :
      types.includes("administrative_area_level_1") ? 12 :
      types.includes("_latlng") ? defaultZoom :
      18;
    window.dispatchEvent(new CustomEvent("lepton:pan-to", { detail: { lat, lng, zoom, label }}));
    if (!skipSetPending) {
      window.LEPTON_LOAD.setPending({ lat, lng, label, source: "search" });
    }
  };

  const pickSuggestion = async (s) => {
    setOpen(false);
    setQuery("");
    setSuggestions([]);
    if (s.synthetic) {
      // Direct lat-lng entry — no Places lookup needed.
      panAndMaybePin(s.lat, s.lng, s.description, ["_latlng"]);
      return;
    }
    try {
      const r = await fetch(`/api/places/details?place_id=${encodeURIComponent(s.place_id)}`);
      const j = await r.json();
      const loc = j.result?.geometry?.location;
      if (loc) {
        const types = j.result?.types || s.types || [];
        panAndMaybePin(loc.lat, loc.lng, s.description, types);
      }
    } catch (e) { console.error(e); }
  };

  const onKeyDown = (e) => {
    if (!open || !suggestions.length) {
      if (e.key === "Escape") inputRef.current?.blur();
      return;
    }
    if (e.key === "ArrowDown") { e.preventDefault(); setHighlight(h => Math.min(suggestions.length - 1, h + 1)); }
    else if (e.key === "ArrowUp") { e.preventDefault(); setHighlight(h => Math.max(0, h - 1)); }
    else if (e.key === "Enter") { e.preventDefault(); pickSuggestion(suggestions[highlight]); }
    else if (e.key === "Escape") { e.preventDefault(); setOpen(false); inputRef.current?.blur(); }
  };

  const hasQuery = query.length > 0;

  return (
    <div className="addrbar" style={{ position: "absolute" }}>
      <div
        className="addrfield"
        style={{
          position: "relative",
          padding: "10px 12px",
          gap: 10,
          boxShadow: focused ? "0 4px 14px rgba(0,0,0,0.10)" : "0 2px 6px rgba(0,0,0,0.04)",
          borderColor: focused ? "var(--ink-3)" : "var(--line-strong)",
          transition: "box-shadow 0.12s, border-color 0.12s",
        }}
      >
        <Icon name="search" size={16} color={focused ? "var(--ink-1)" : "var(--ink-3)"}/>
        <input
          ref={inputRef}
          type="text"
          value={query}
          onChange={onChange}
          onFocus={() => { setFocused(true); if (suggestions.length) setOpen(true); }}
          onBlur={() => { setFocused(false); setTimeout(() => setOpen(false), 150); }}
          onKeyDown={onKeyDown}
          placeholder={placeholder}
          autoComplete="off"
          spellCheck={false}
          style={{
            border: 0, outline: 0, background: "transparent",
            fontSize: 13.5, color: "var(--ink-1)", flex: 1, minWidth: 0,
            fontFamily: "inherit", padding: 0,
          }}
        />
        {hasQuery && (
          <button
            onMouseDown={(e) => { e.preventDefault(); clear(); }}
            title="Clear (Esc)"
            style={{
              border: 0, background: "transparent", cursor: "pointer",
              padding: 4, borderRadius: 4, display: "inline-flex",
              color: "var(--ink-3)",
            }}
            onMouseEnter={(e) => e.currentTarget.style.background = "var(--bg-sunken)"}
            onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}
          >
            <Icon name="x" size={14} color="currentColor"/>
          </button>
        )}
      </div>
      {open && suggestions.length > 0 && (
        <div style={{
          position: "absolute", top: "calc(100% + 4px)", left: 0, right: 0,
          background: "var(--bg-elev)", border: "1px solid var(--line-strong)",
          borderRadius: 9, boxShadow: "0 12px 32px rgba(0,0,0,0.12)",
          zIndex: 1001, overflow: "hidden",
          padding: "4px 0",
        }}>
          {suggestions.map((s, i) => (
            <div
              key={s.place_id}
              onMouseDown={(e) => { e.preventDefault(); pickSuggestion(s); }}
              onMouseEnter={() => setHighlight(i)}
              style={{
                padding: "10px 14px", cursor: "pointer",
                display: "flex", alignItems: "center", gap: 12,
                background: i === highlight ? "var(--bg-sunken)" : "transparent",
                transition: "background 0.08s",
              }}
            >
              <div style={{
                width: 28, height: 28, borderRadius: 14,
                background: "var(--bg-sunken)", display: "grid", placeItems: "center",
                color: "var(--ink-2)", flexShrink: 0,
              }}>
                <Icon name={iconForPlaceTypes(s.types)} size={13} color="currentColor"/>
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{
                  fontSize: 13, color: "var(--ink-1)", fontWeight: 500,
                  whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis",
                  marginBottom: 2,
                }}>
                  {s.main}
                </div>
                {s.secondary && (
                  <div style={{
                    fontSize: 11.5, color: "var(--ink-3)",
                    whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis",
                  }}>
                    {s.secondary}
                  </div>
                )}
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

// Floating pill on the map for switching to polygon-draw mode.
// Sits bottom-left so it doesn't compete with the search box at the top.
function PolygonToggle({ selectionMode }) {
  const isDrawing = selectionMode === "polygon";
  const toggle = () => {
    if (isDrawing) {
      window.LEPTON_LOAD.setSelectionMode("pin");
    } else {
      window.LEPTON_LOAD.setSelectionMode("polygon");
      window.LEPTON_LOAD.setPolygon(null);
    }
  };
  return (
    <div style={{ position: "absolute", left: 268, bottom: 14, zIndex: 999 }}>
      <button
        onClick={toggle}
        title={isDrawing ? "Exit polygon mode (Esc)" : "Draw a custom building outline"}
        style={{
          border: "1px solid " + (isDrawing ? "var(--ink-1)" : "var(--line-strong)"),
          background: isDrawing ? "var(--ink-1)" : "var(--bg-elev)",
          color: isDrawing ? "white" : "var(--ink-2)",
          padding: "8px 14px", borderRadius: 22, cursor: "pointer",
          fontFamily: "inherit", fontSize: 12,
          display: "inline-flex", alignItems: "center", gap: 8,
          boxShadow: "0 2px 8px rgba(0,0,0,0.06)",
          whiteSpace: "nowrap",
        }}
      >
        <Icon name="diamond" size={12} color="currentColor"/>
        {isDrawing ? "Drawing · click vertices, close at start" : "Draw polygon"}
      </button>
    </div>
  );
}

window.HomeownerMode = HomeownerMode;
// Shared with CityMode so the polygon-draw control + search-bar are identical across tabs.
window.PolygonToggle = PolygonToggle;
window.AddrBar = AddrBar;
