// Bill Calculator — responsive 2-column layout: hero on top, inputs left, results right.

function BillCalculator() {
  const { appliances, setAppliances, rate, setRate, goSolar, tweaks } =
    React.useContext(window.AppContext);
  const [sheetOpen, setSheetOpen] = React.useState(false);
  const [editing, setEditing] = React.useState(null);

  // ---- Derived ----
  const perApp = appliances.map((a) => {
    const hrs = hoursBetween(a.start, a.end);
    const kWhDay = (a.wattage * hrs) / 1000;
    const kWhMonth = kWhDay * 30;
    return { ...a, hrs, kWhDay, kWhMonth };
  });
  const totalUnits = perApp.reduce((s, a) => s + a.kWhMonth, 0);
  const bill = computeBill(totalUnits, rate);

  // Track bill calculation (debounced 1.5s after last change)
  React.useEffect(() => {
    if (!bill.cost || bill.cost <= 0) return;
    const t = setTimeout(() => {
      if (window.gtag) window.gtag('event', 'bill_calculated', {
        calculator_type: 'electricity',
        bill_tier: Math.round(bill.cost / 1000),
      });
    }, 1500);
    return () => clearTimeout(t);
  }, [bill.cost]);

  const openAdd = () => { setEditing(null); setSheetOpen(true); };
  const openEdit = (a) => { setEditing(a); setSheetOpen(true); };
  const remove = (id) => setAppliances((xs) => xs.filter((x) => x.id !== id));
  const upsert = (a) => {
    setAppliances((xs) => {
      const i = xs.findIndex((x) => x.id === a.id);
      if (i === -1) return [...xs, a];
      const next = xs.slice(); next[i] = a; return next;
    });
    setSheetOpen(false);
  };

  return (
    <>
      {/* HERO BAND — full viewport width, content within max-width */}
      <div className="hero-band">
        <div className="app-shell">
          <BillHero units={totalUnits} bill={bill} rate={rate} perApp={perApp}
                    currency={tweaks.currencySymbol} count={appliances.length}/>
        </div>
      </div>

      {/* TWO-COLUMN BODY */}
      <div className="page-wrap">
        <div className="page-grid">
          {/* LEFT — inputs */}
          <div className="col col-pad">
            <Section
              title="Your appliances"
              hint={`${appliances.length} item${appliances.length === 1 ? "" : "s"} · ${fmtUnits(totalUnits)} units/mo`}
              action={
                <button onClick={openAdd} style={{
                  display: "inline-flex", alignItems: "center", gap: 6,
                  padding: "7px 12px", borderRadius: 999,
                  background: "var(--fg)", color: "var(--surface)",
                  fontSize: 13, fontWeight: 500,
                }}>
                  <IconPlus size={13} stroke={2}/> Add appliance
                </button>
              }
            >
              {appliances.length === 0 ? (
                <EmptyState onAdd={openAdd}/>
              ) : (
                <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                  {perApp.map((a) => (
                    <ApplianceCard key={a.id} a={a} totalUnits={totalUnits}
                                   rate={rate} currency={tweaks.currencySymbol}
                                   compact={tweaks.compactCards}
                                   onEdit={() => openEdit(a)}
                                   onDelete={() => remove(a.id)} />
                  ))}
                </div>
              )}
            </Section>

            <Section title="Electricity rate"
                     hint="What you pay per unit (1 unit = 1 kWh)">
              <Toggle full
                      options={[{ value: "flat", label: "Flat rate" }, { value: "slab", label: "Slab tiers" }]}
                      value={rate.mode}
                      onChange={(v) => setRate({ ...rate, mode: v })} />

              {rate.mode === "flat" ? (
                <div style={{ marginTop: 14 }}>
                  <NumberField large prefix={tweaks.currencySymbol} suffix="/unit"
                               value={rate.flat} min={0} step={0.5}
                               onChange={(v) => setRate({ ...rate, flat: Number(v) || 0 })} />
                  {tweaks.showTips && (
                    <div style={{ marginTop: 10, fontSize: 12, color: "var(--muted)" }}>
                      Typical 2025 K-Electric / WAPDA flat rates land around Rs. 35–48 per unit after taxes & fuel adjustment.
                    </div>
                  )}
                </div>
              ) : (
                <SlabEditor rate={rate} setRate={setRate} currency={tweaks.currencySymbol}
                            currentUnits={totalUnits} />
              )}
            </Section>
          </div>

          {/* RIGHT — results, sticky on desktop */}
          <div className="col col-pad sticky-right">
            <AdSlot slot="electricity" style={{ margin: "4px 18px 0" }} />

            {appliances.length > 0 && (
              <Section title="Where the bill goes"
                       hint="Estimated per appliance at this usage pattern">
                <div style={{ marginTop: 4 }}>
                  {[...perApp]
                    .sort((a, b) => b.kWhMonth - a.kWhMonth)
                    .map((a) => (
                      <BreakdownRow key={a.id} a={a} totalUnits={totalUnits}
                                    effectiveRate={bill.effectiveRate}
                                    currency={tweaks.currencySymbol} />
                    ))}
                </div>
                <BreakdownTotal totalUnits={totalUnits} bill={bill}
                                currency={tweaks.currencySymbol}/>
                <div style={{ marginTop: 12 }}>
                  <PrimaryButton full variant="ghost" icon={<IconShare size={14}/>}
                    onClick={() => {
                      if (window.gtag) window.gtag('event', 'share_clicked', { calculator_type: 'electricity' });
                      const txt = `My electricity estimate: ${fmtUnits(totalUnits)} units/mo, ${tweaks.currencySymbol} ${fmtPKR(bill.cost, {symbol:""}).trim()}/mo | Pak Bill Calculator`;
                      if (navigator.share) { navigator.share({ title: "My bill estimate", text: txt }).catch(() => {}); }
                      else if (navigator.clipboard) { navigator.clipboard.writeText(txt); }
                    }}>
                    Share my estimate
                  </PrimaryButton>
                </div>
              </Section>
            )}

            <Section style={{ borderBottom: "none" }}>
              <div style={{
                padding: 18, borderRadius: "var(--radius-lg)",
                background: "linear-gradient(135deg, var(--solar-soft), var(--surface) 70%)",
                border: "1px solid var(--border-soft)",
                display: "flex", flexDirection: "column", gap: 14,
              }}>
                <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
                  <div style={{ width: 36, height: 36, borderRadius: 999, background: "var(--solar)",
                                color: "white", display: "grid", placeItems: "center" }}>
                    <IconSun size={18} stroke={2}/>
                  </div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 15, fontWeight: 600, color: "var(--fg)" }}>
                      Could solar pay this off?
                    </div>
                    <div style={{ fontSize: 12, color: "var(--muted)", marginTop: 2 }}>
                      System size, install cost, payback period
                    </div>
                  </div>
                </div>
                <PrimaryButton onClick={goSolar} full
                               icon={<IconChevron size={13} stroke={2}/>}>
                  Estimate solar ROI
                </PrimaryButton>
              </div>
            </Section>
          </div>
        </div>
      </div>

      <Sheet open={sheetOpen} onClose={() => setSheetOpen(false)}
             title={editing ? "Edit appliance" : "Add appliance"}>
        <ApplianceForm editing={editing} onSave={upsert}
                       onDelete={editing ? () => { remove(editing.id); setSheetOpen(false); } : null} />
      </Sheet>
    </>
  );
}

// ---------- Bill engine -----------------------------------------------------

function computeBill(units, rate) {
  if (units <= 0) return { cost: 0, tier: null, effectiveRate: rate.mode === "flat" ? rate.flat : 0 };
  if (rate.mode === "flat") {
    return { cost: units * rate.flat, tier: null, effectiveRate: rate.flat };
  }
  let remaining = units, cost = 0, tierIdx = 0;
  let prev = 0;
  for (let i = 0; i < rate.slabs.length; i++) {
    const slab = rate.slabs[i];
    const upTo = slab.upTo === null ? Infinity : slab.upTo;
    const span = upTo - prev;
    const used = Math.min(remaining, span);
    cost += used * slab.rate;
    if (used > 0) tierIdx = i;
    remaining -= used;
    prev = upTo;
    if (remaining <= 0.0001) break;
  }
  return { cost, tier: tierIdx, effectiveRate: cost / units };
}

// ---------- Hero (big bill number + side stats) ----------------------------

function BillHero({ units, bill, rate, perApp, currency, count }) {
  const tierLabel = bill.tier !== null
    ? `Slab ${bill.tier + 1}${rate.slabs[bill.tier].upTo ? ` · up to ${rate.slabs[bill.tier].upTo} units` : " · 700+ units"}`
    : `Flat ${currency} ${rate.flat}/unit`;

  return (
    <div className="hero-row">
      {/* Left half: label + big number + pills */}
      <div>
        <div style={{ ...ss.label, marginBottom: 8 }}>Estimated monthly bill</div>
        <div style={{ display: "flex", alignItems: "baseline", gap: 6, flexWrap: "wrap" }}>
          <span className="serif" style={{ fontSize: 48, lineHeight: 1, fontWeight: 400,
                                            color: "var(--fg-2)", letterSpacing: "-0.02em" }}>
            {currency}
          </span>
          <span className="mono" style={{ fontSize: 72, lineHeight: 1, fontWeight: 500,
                                           color: "var(--fg)", letterSpacing: "-0.03em" }}>
            {bill.cost ? fmtPKR(bill.cost, { symbol: "" }).trim() : "0"}
          </span>
        </div>
        <div style={{ display: "flex", gap: 6, marginTop: 16, flexWrap: "wrap" }}>
          <Pill tone="accent">
            <span className="mono">{fmtUnits(units)}</span>&nbsp;units/mo
          </Pill>
          <Pill>{tierLabel}</Pill>
          <Pill tone="ghost">
            <IconBolt size={11}/>&nbsp;{count}&nbsp;{count === 1 ? "appliance" : "appliances"}
          </Pill>
        </div>
        <div className="serif" style={{
          marginTop: 16, fontSize: 17, color: "var(--muted)",
          fontStyle: "italic", maxWidth: 460, lineHeight: 1.35,
        }}>
          {bill.cost > 0
            ? <>That's about <span style={{ color: "var(--fg-2)" }}>{currency}&nbsp;{fmtPKR(bill.cost/30, {symbol:""}).trim()}</span> a day, or <span style={{ color: "var(--fg-2)" }}>{currency}&nbsp;{fmtPKR(bill.cost*12,{symbol:"",compact:true}).trim()}</span> a year.</>
            : <>Add an appliance to see your estimate.</>}
        </div>
      </div>

      {/* Right half: 24h ring + top users */}
      <div style={{
        display: "flex", alignItems: "center", gap: 18,
        padding: 16,
        background: "var(--surface)",
        borderRadius: "var(--radius-lg)",
        border: "1px solid var(--border-soft)",
        boxShadow: "var(--shadow)",
      }}>
        <TimeRing items={perApp.map((a) => ({ start: a.start, end: a.end }))} size={120}/>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div className="mono" style={{ fontSize: 10, color: "var(--muted)",
                                          textTransform: "uppercase", letterSpacing: "0.08em" }}>
            Top loads
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 6, marginTop: 8 }}>
            {[...perApp].sort((a,b)=>b.kWhMonth-a.kWhMonth).slice(0, 3).map((a, i) => {
              const colors = ["#d97706", "#65a30d", "#0891b2"];
              return (
                <div key={a.id} style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 12 }}>
                  <span style={{ width: 8, height: 8, borderRadius: 2, background: colors[i], flexShrink: 0 }}/>
                  <span style={{ flex: 1, color: "var(--fg-2)", whiteSpace: "nowrap",
                                  overflow: "hidden", textOverflow: "ellipsis" }}>{a.type}</span>
                  <span className="mono" style={{ color: "var(--muted)" }}>
                    {Math.round((a.kWhMonth/Math.max(1,units))*100)}%
                  </span>
                </div>
              );
            })}
            {perApp.length === 0 && (
              <div style={{ fontSize: 12, color: "var(--muted)" }}>-</div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

// ---------- Empty state -----------------------------------------------------

function EmptyState({ onAdd }) {
  return (
    <div style={{
      padding: "28px 16px",
      textAlign: "center",
      border: "1px dashed var(--border)",
      borderRadius: "var(--radius)",
      background: "var(--bg-2)",
    }}>
      <div className="serif" style={{ fontSize: 22, lineHeight: 1.15, color: "var(--fg-2)" }}>
        Nothing plugged in yet.
      </div>
      <div style={{ fontSize: 13, color: "var(--muted)", marginTop: 6, marginBottom: 14 }}>
        Add an AC, fridge, or whatever's burning the most current.
      </div>
      <PrimaryButton onClick={onAdd} icon={<IconPlus size={14} stroke={2}/>}>
        Add appliance
      </PrimaryButton>
    </div>
  );
}

// ---------- Appliance row card ---------------------------------------------

function ApplianceCard({ a, totalUnits, rate, currency, compact, onEdit, onDelete }) {
  const monthlyCost = computeApplianceCost(a, totalUnits, rate);
  const pct = totalUnits > 0 ? (a.kWhMonth / totalUnits) * 100 : 0;

  return (
    <div onClick={onEdit} style={{
      padding: compact ? 12 : 14,
      borderRadius: "var(--radius)",
      border: "1px solid var(--border-soft)",
      background: "var(--surface)",
      cursor: "pointer",
      transition: "border-color .15s, box-shadow .15s",
    }}
    onMouseEnter={(e) => { e.currentTarget.style.borderColor = "var(--border)"; e.currentTarget.style.boxShadow = "var(--shadow-sm)"; }}
    onMouseLeave={(e) => { e.currentTarget.style.borderColor = "var(--border-soft)"; e.currentTarget.style.boxShadow = "none"; }}>

      <div style={{ display: "flex", alignItems: "flex-start", gap: 12 }}>
        <CategoryGlyph cat={a.category}/>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 14, fontWeight: 600, color: "var(--fg)",
                        whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
            {a.type}
          </div>
          <div style={{ fontSize: 12, color: "var(--muted)", marginTop: 1,
                        whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
            {a.brand} {a.model}
          </div>
        </div>
        <div style={{ textAlign: "right" }}>
          <div className="mono" style={{ fontSize: 15, fontWeight: 600, color: "var(--fg)" }}>
            {fmtPKR(monthlyCost, { symbol: currency })}
          </div>
          <div className="mono" style={{ fontSize: 11, color: "var(--muted)" }}>
            {fmtUnits(a.kWhMonth)} units
          </div>
        </div>
      </div>

      {!compact && (
        <div style={{ display: "flex", gap: 8, marginTop: 12, alignItems: "center" }}>
          <ChipRange icon={<IconBolt size={11}/>}>{a.wattage}W</ChipRange>
          <ChipRange icon={<IconClock size={11}/>}>{a.start}–{a.end} · {fmtUnits(a.hrs)}h</ChipRange>
          <div style={{ flex: 1, height: 4, borderRadius: 999, background: "var(--bg-2)", overflow: "hidden", minWidth: 24 }}>
            <div style={{ width: `${Math.min(100, pct)}%`, height: "100%",
                          background: "var(--accent)", transition: "width .3s" }}/>
          </div>
          <button onClick={(e) => { e.stopPropagation(); onDelete(); }}
                  aria-label="Remove" style={{
            width: 26, height: 26, borderRadius: 999, color: "var(--muted-2)",
            display: "grid", placeItems: "center",
          }}
            onMouseEnter={(e) => { e.currentTarget.style.background = "var(--bg-2)"; e.currentTarget.style.color = "var(--danger)"; }}
            onMouseLeave={(e) => { e.currentTarget.style.background = "transparent"; e.currentTarget.style.color = "var(--muted-2)"; }}>
            <IconTrash size={14}/>
          </button>
        </div>
      )}
    </div>
  );
}

function ChipRange({ icon, children }) {
  return (
    <span className="mono" style={{
      display: "inline-flex", alignItems: "center", gap: 4,
      fontSize: 11, color: "var(--muted)",
      padding: "3px 7px", borderRadius: 6,
      background: "var(--bg-2)",
    }}>{icon}{children}</span>
  );
}

function computeApplianceCost(a, totalUnits, rate) {
  if (totalUnits <= 0) return 0;
  const totalBill = computeBill(totalUnits, rate).cost;
  return totalBill * (a.kWhMonth / totalUnits);
}

// ---------- Category glyphs (tiny) -----------------------------------------

function CategoryGlyph({ cat }) {
  const map = {
    Cooling:       { bg: "oklch(0.93 0.05 220)", fg: "oklch(0.35 0.12 220)" },
    Kitchen:       { bg: "oklch(0.93 0.05 60)",  fg: "oklch(0.35 0.13 50)" },
    Bathroom:      { bg: "oklch(0.93 0.04 200)", fg: "oklch(0.4 0.1 200)" },
    Lighting:      { bg: "oklch(0.95 0.07 90)",  fg: "oklch(0.45 0.14 80)" },
    Laundry:       { bg: "oklch(0.93 0.04 280)", fg: "oklch(0.4 0.1 280)" },
    Entertainment: { bg: "oklch(0.93 0.05 320)", fg: "oklch(0.4 0.11 320)" },
    Office:        { bg: "oklch(0.93 0.03 30)",  fg: "oklch(0.4 0.08 30)" },
    Other:         { bg: "var(--bg-2)", fg: "var(--muted)" },
  };
  const c = map[cat] || map.Other;
  return (
    <div style={{
      width: 36, height: 36, flexShrink: 0,
      borderRadius: 10, background: c.bg, color: c.fg,
      display: "grid", placeItems: "center",
      fontFamily: "var(--font-mono)", fontSize: 11, fontWeight: 600,
      letterSpacing: "0.04em",
    }}>{cat.slice(0,2).toUpperCase()}</div>
  );
}

// ---------- Slab editor ----------------------------------------------------

function SlabEditor({ rate, setRate, currency, currentUnits }) {
  const update = (i, val) => {
    const next = rate.slabs.map((s, j) => j === i ? { ...s, rate: Number(val) || 0 } : s);
    setRate({ ...rate, slabs: next });
  };
  return (
    <div style={{ marginTop: 14, display: "flex", flexDirection: "column", gap: 8 }}>
      {rate.slabs.map((s, i) => {
        const lower = i === 0 ? 1 : rate.slabs[i-1].upTo + 1;
        const active = currentUnits >= lower;
        return (
          <div key={i} style={{
            display: "grid", gridTemplateColumns: "1fr auto",
            alignItems: "center", gap: 10,
            padding: "8px 12px",
            border: `1px solid ${active ? "var(--accent)" : "var(--border-soft)"}`,
            borderRadius: "var(--radius-sm)",
            background: active ? "oklch(0.99 0.02 75)" : "var(--surface)",
            transition: "all .15s",
          }}>
            <div>
              <div className="mono" style={{ fontSize: 11, color: "var(--muted)", letterSpacing: "0.05em", textTransform: "uppercase" }}>
                Slab {i+1}
              </div>
              <div style={{ fontSize: 13, color: "var(--fg-2)", marginTop: 1 }}>
                {lower}{s.upTo === null ? "+" : `–${s.upTo}`} units
              </div>
            </div>
            <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
              <span className="mono" style={{ fontSize: 12, color: "var(--muted)" }}>{currency}</span>
              <input type="number" value={s.rate} step={0.5} min={0}
                     onChange={(e) => update(i, e.target.value)}
                     className="mono"
                     style={{
                       width: 60, textAlign: "right",
                       padding: "6px 8px", fontSize: 14, fontWeight: 500,
                       background: "var(--surface)", border: "1px solid var(--border)",
                       borderRadius: 6, color: "var(--fg)",
                     }}/>
              <span style={{ fontSize: 11, color: "var(--muted)" }}>/u</span>
            </div>
          </div>
        );
      })}
    </div>
  );
}

// ---------- Breakdown rows -------------------------------------------------

function BreakdownRow({ a, totalUnits, effectiveRate, currency }) {
  const cost = a.kWhMonth * effectiveRate;
  const pct = totalUnits > 0 ? (a.kWhMonth / totalUnits) * 100 : 0;
  return (
    <div style={{ padding: "10px 0", borderBottom: "1px dashed var(--border-soft)" }}>
      <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", marginBottom: 6, gap: 12 }}>
        <div style={{ fontSize: 13, color: "var(--fg)",
                      whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{a.type}</div>
        <div className="mono" style={{ fontSize: 13, fontWeight: 500, color: "var(--fg)", flexShrink: 0 }}>
          {fmtPKR(cost, { symbol: currency })}
        </div>
      </div>
      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
        <div style={{ flex: 1, height: 3, borderRadius: 999, background: "var(--bg-2)", overflow: "hidden" }}>
          <div style={{
            width: `${Math.min(100, pct)}%`, height: "100%",
            background: "var(--fg-2)",
          }}/>
        </div>
        <div className="mono" style={{ fontSize: 11, color: "var(--muted)", width: 38, textAlign: "right" }}>
          {pct.toFixed(0)}%
        </div>
      </div>
    </div>
  );
}

function BreakdownTotal({ totalUnits, bill, currency }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline",
                  marginTop: 12, paddingTop: 12, borderTop: "1px solid var(--border)" }}>
      <div>
        <div style={{ fontSize: 13, fontWeight: 600 }}>Total</div>
        <div className="mono" style={{ fontSize: 11, color: "var(--muted)" }}>
          {fmtUnits(totalUnits)} units · avg {currency} {bill.effectiveRate.toFixed(2)}/unit
        </div>
      </div>
      <div className="mono" style={{ fontSize: 22, fontWeight: 600, color: "var(--fg)" }}>
        {fmtPKR(bill.cost, { symbol: currency })}
      </div>
    </div>
  );
}

// ---------- Add / Edit form (sheet body) -----------------------------------

function ApplianceForm({ editing, onSave, onDelete }) {
  const [mode, setMode] = React.useState(editing ? "manual" : "search");
  const [query, setQuery] = React.useState("");
  const [draft, setDraft] = React.useState(editing || {
    id: `a${Date.now()}`,
    brand: "", model: "", type: "", category: "Cooling",
    wattage: 100, start: "20:00", end: "23:00",
  });

  const matches = React.useMemo(() => {
    if (!query.trim()) return window.APPLIANCES.slice(0, 8);
    const q = query.toLowerCase();
    return window.APPLIANCES.filter((a) =>
      (a.brand + " " + a.model + " " + a.type).toLowerCase().includes(q)
    ).slice(0, 12);
  }, [query]);

  const pickFromDb = (a) => {
    setDraft({
      id: draft.id, brand: a.brand, model: a.model, type: a.type,
      category: a.category, wattage: a.wattage,
      start: a.defaultStart, end: a.defaultEnd,
    });
    setMode("manual");
  };

  const hrs = hoursBetween(draft.start, draft.end);
  const kWhDay = (draft.wattage * hrs) / 1000;

  const canSave = draft.wattage > 0 && draft.type.trim().length > 0;

  return (
    <div style={{ padding: 16, display: "flex", flexDirection: "column", gap: 14 }}>
      {!editing && (
        <Toggle full
                options={[{ value: "search", label: "Pick from list" }, { value: "manual", label: "Enter manually" }]}
                value={mode}
                onChange={setMode} />
      )}

      {mode === "search" && (
        <>
          <div style={{
            display: "flex", alignItems: "center", gap: 8,
            padding: "10px 12px", border: "1px solid var(--border)", borderRadius: "var(--radius-sm)",
            background: "var(--surface)",
          }}>
            <IconSearch size={16} stroke={1.6} style={{ color: "var(--muted)" }}/>
            <input autoFocus
                   placeholder="Search brand, model or type…"
                   value={query}
                   onChange={(e) => setQuery(e.target.value)}
                   style={{ flex: 1, border: "none", background: "transparent", fontSize: 14, padding: "2px 0" }}/>
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 4, maxHeight: 320, overflowY: "auto" }}>
            {matches.map((a, i) => (
              <button key={i} onClick={() => pickFromDb(a)} style={{
                textAlign: "left", padding: "10px 12px", borderRadius: 10,
                background: "transparent",
                transition: "background .12s",
              }}
                onMouseEnter={(e) => e.currentTarget.style.background = "var(--bg-2)"}
                onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
                  <div style={{ fontSize: 14, fontWeight: 500, color: "var(--fg)" }}>{a.type}</div>
                  <div className="mono" style={{ fontSize: 12, color: "var(--accent-ink)" }}>{a.wattage}W</div>
                </div>
                <div style={{ fontSize: 12, color: "var(--muted)" }}>{a.brand} · {a.model}</div>
              </button>
            ))}
            {matches.length === 0 && (
              <div style={{ padding: 20, textAlign: "center", color: "var(--muted)", fontSize: 13 }}>
                No matches. <button onClick={() => setMode("manual")}
                  style={{ color: "var(--fg)", textDecoration: "underline" }}>Enter manually →</button>
              </div>
            )}
          </div>
        </>
      )}

      {mode === "manual" && (
        <>
          <FormField label="Name / type">
            <input value={draft.type} onChange={(e) => setDraft({ ...draft, type: e.target.value })}
                   placeholder="e.g. AC 1.5 Ton Inverter" style={ss.input}/>
          </FormField>

          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
            <FormField label="Brand">
              <input value={draft.brand} onChange={(e) => setDraft({ ...draft, brand: e.target.value })}
                     placeholder="Haier" style={ss.input}/>
            </FormField>
            <FormField label="Model">
              <input value={draft.model} onChange={(e) => setDraft({ ...draft, model: e.target.value })}
                     placeholder="HSU-18..." style={ss.input}/>
            </FormField>
          </div>

          <FormField label="Category">
            <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
              {window.APPLIANCE_CATEGORIES.map((c) => (
                <button key={c} onClick={() => setDraft({ ...draft, category: c })} style={{
                  padding: "6px 11px", borderRadius: 999,
                  fontSize: 12, fontWeight: 500,
                  background: draft.category === c ? "var(--fg)" : "var(--bg-2)",
                  color: draft.category === c ? "var(--surface)" : "var(--fg-2)",
                  border: "1px solid transparent",
                }}>{c}</button>
              ))}
            </div>
          </FormField>

          <FormField label="Wattage" hint="From the spec sticker on the appliance">
            <NumberField suffix="W" mono value={draft.wattage} min={1} step={10}
                         onChange={(v) => setDraft({ ...draft, wattage: Number(v) || 0 })}/>
          </FormField>

          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
            <FormField label="Starts at">
              <input type="time" value={draft.start} className="mono"
                     onChange={(e) => setDraft({ ...draft, start: e.target.value })} style={ss.input}/>
            </FormField>
            <FormField label="Ends at">
              <input type="time" value={draft.end} className="mono"
                     onChange={(e) => setDraft({ ...draft, end: e.target.value })} style={ss.input}/>
            </FormField>
          </div>

          <div style={{
            padding: 14, borderRadius: "var(--radius)",
            background: "var(--bg-2)", border: "1px solid var(--border-soft)",
            display: "flex", alignItems: "center", gap: 14,
          }}>
            <TimeRing items={[{ start: draft.start, end: draft.end }]} size={86}/>
            <div style={{ flex: 1 }}>
              <div className="mono" style={{ fontSize: 10, color: "var(--muted)", textTransform: "uppercase", letterSpacing: "0.06em" }}>Daily runtime</div>
              <div style={{ display: "flex", alignItems: "baseline", gap: 4, marginTop: 2 }}>
                <span className="mono" style={{ fontSize: 28, fontWeight: 600, color: "var(--fg)" }}>{fmtUnits(hrs)}</span>
                <span style={{ fontSize: 13, color: "var(--muted)" }}>hours</span>
              </div>
              <div style={{ fontSize: 12, color: "var(--muted)", marginTop: 4 }}>
                → <span className="mono" style={{ color: "var(--fg-2)" }}>{fmtUnits(kWhDay)}</span> units/day,
                <span className="mono" style={{ color: "var(--fg-2)" }}> {fmtUnits(kWhDay*30)}</span>/month
              </div>
            </div>
          </div>

          <div style={{ display: "flex", gap: 8, marginTop: 4 }}>
            {onDelete && (
              <PrimaryButton onClick={onDelete} variant="ghost"
                             icon={<IconTrash size={14}/>}
                             style={{ color: "var(--danger)", borderColor: "var(--border)" }}>
                Remove
              </PrimaryButton>
            )}
            <PrimaryButton onClick={() => onSave(draft)} disabled={!canSave} full>
              {editing ? "Save changes" : "Add to list"}
            </PrimaryButton>
          </div>
        </>
      )}
    </div>
  );
}

function FormField({ label, hint, children }) {
  return (
    <label style={{ display: "flex", flexDirection: "column", gap: 6 }}>
      <span style={ss.label}>{label}</span>
      {children}
      {hint && <span style={{ fontSize: 11, color: "var(--muted-2)" }}>{hint}</span>}
    </label>
  );
}

Object.assign(window, { BillCalculator, computeBill });
