// Gas Bill Calculator — same layout pattern as BillCalculator.

const GAS_APPLIANCE_CATALOG = [
  { type: "Cooking Stove 2-Ring",   category: "Kitchen",  consumptionM3PerHour: 0.30, defaultHours: 2,    defaultMonths: 12 },
  { type: "Cooking Stove 3-Ring",   category: "Kitchen",  consumptionM3PerHour: 0.45, defaultHours: 2,    defaultMonths: 12 },
  { type: "Cooking Stove 4-Ring",   category: "Kitchen",  consumptionM3PerHour: 0.60, defaultHours: 2.5,  defaultMonths: 12 },
  { type: "Tandoor / Roti Maker",   category: "Kitchen",  consumptionM3PerHour: 1.50, defaultHours: 0.5,  defaultMonths: 12 },
  { type: "Instant Gas Geyser",     category: "Bathroom", consumptionM3PerHour: 0.80, defaultHours: 0.75, defaultMonths: 12 },
  { type: "Storage Gas Geyser",     category: "Bathroom", consumptionM3PerHour: 1.20, defaultHours: 1,    defaultMonths: 12 },
  { type: "Room Heater (Gas)",      category: "Heating",  consumptionM3PerHour: 1.20, defaultHours: 8,    defaultMonths: 4  },
  { type: "Gas Fireplace",          category: "Heating",  consumptionM3PerHour: 2.00, defaultHours: 4,    defaultMonths: 4  },
  { type: "Gas Dryer",              category: "Laundry",  consumptionM3PerHour: 0.50, defaultHours: 1,    defaultMonths: 12 },
];

const GAS_CATEGORIES = ["Kitchen", "Bathroom", "Heating", "Laundry", "Other"];

const GAS_PROVIDERS = {
  sngpl: {
    label: "SNGPL (Sui Northern)",
    fixedCharges: 200,
    slabs: [
      { fromM3: 0,   toM3: 25,   rate: 128  },
      { fromM3: 25,  toM3: 50,   rate: 338  },
      { fromM3: 50,  toM3: 100,  rate: 973  },
      { fromM3: 100, toM3: null, rate: 1107 },
    ],
  },
  ssgc: {
    label: "SSGC (Sui Southern)",
    fixedCharges: 200,
    slabs: [
      { fromM3: 0,   toM3: 25,   rate: 128  },
      { fromM3: 25,  toM3: 50,   rate: 338  },
      { fromM3: 50,  toM3: 100,  rate: 973  },
      { fromM3: 100, toM3: null, rate: 1107 },
    ],
  },
};

const SEED_GAS = [
  { id: "g1", type: "Cooking Stove 3-Ring", category: "Kitchen",  consumptionM3PerHour: 0.45, hoursPerDay: 2,    monthsPerYear: 12 },
  { id: "g2", type: "Instant Gas Geyser",   category: "Bathroom", consumptionM3PerHour: 0.80, hoursPerDay: 0.75, monthsPerYear: 12 },
  { id: "g3", type: "Room Heater (Gas)",    category: "Heating",  consumptionM3PerHour: 1.20, hoursPerDay: 6,    monthsPerYear: 4  },
];

// ---- Engine ----------------------------------------------------------------

function computeGasBill(appliances, rate, fixedCharges) {
  const perApp = appliances.map((a) => {
    // seasonal amortisation: monthsPerYear/12 factor
    const m3 = a.consumptionM3PerHour * a.hoursPerDay * 30 * (a.monthsPerYear / 12);
    return { ...a, m3 };
  });
  const totalM3 = perApp.reduce((s, a) => s + a.m3, 0);

  let variableCost = 0;
  let slabTier = null;

  if (rate.mode === "flat") {
    variableCost = totalM3 * rate.flat;
  } else {
    let remaining = totalM3;
    for (let i = 0; i < rate.slabs.length; i++) {
      if (remaining <= 0.0001) break;
      const s = rate.slabs[i];
      const capacity = s.toM3 !== null ? s.toM3 - s.fromM3 : Infinity;
      const used = Math.min(remaining, capacity);
      variableCost += used * s.rate;
      if (used > 0) slabTier = i;
      remaining -= used;
    }
  }

  const totalBill = variableCost + fixedCharges;
  const isProtected = totalM3 <= 90;

  const perAppCost = perApp.map((a) => ({
    ...a,
    cost: totalM3 > 0 ? (a.m3 / totalM3) * variableCost : 0,
    pct:  totalM3 > 0 ? (a.m3 / totalM3) * 100 : 0,
  }));

  return { perApp: perAppCost, totalM3, variableCost, fixedCost: fixedCharges, totalBill, slabTier, isProtected };
}

// ---- Main component --------------------------------------------------------

function GasBill() {
  const { tweaks } = React.useContext(window.AppContext);
  const [appliances, setAppliances] = React.useState(SEED_GAS);
  const [provider, setProvider] = React.useState("sngpl");
  const [rate, setRate] = React.useState({
    mode: "slab",
    flat: 300,
    slabs: GAS_PROVIDERS.sngpl.slabs,
  });
  const [fixedCharges, setFixedCharges] = React.useState(200);
  const [sheetOpen, setSheetOpen] = React.useState(false);
  const [editing, setEditing] = React.useState(null);

  const result = computeGasBill(appliances, rate, fixedCharges);

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

  const applyProvider = (key) => {
    const p = GAS_PROVIDERS[key];
    setProvider(key);
    setRate((r) => ({ ...r, mode: "slab", slabs: p.slabs }));
    setFixedCharges(p.fixedCharges);
  };

  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 */}
      <div className="hero-band">
        <div className="app-shell">
          <GasHero result={result} 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="Gas appliances"
              hint={`${appliances.length} item${appliances.length === 1 ? "" : "s"} · ${fmtUnits(result.totalM3)} m³/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 ? (
                <GasEmptyState onAdd={openAdd} />
              ) : (
                <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                  {result.perApp.map((a) => (
                    <GasApplianceCard key={a.id} a={a} totalM3={result.totalM3}
                                      currency={tweaks.currencySymbol}
                                      compact={tweaks.compactCards}
                                      onEdit={() => openEdit(a)}
                                      onDelete={() => remove(a.id)} />
                  ))}
                </div>
              )}
            </Section>

            <Section title="Gas tariff" hint="Your utility provider rates">
              {/* Provider quick-select */}
              <div style={{ display: "flex", gap: 6, marginBottom: 14 }}>
                {Object.entries(GAS_PROVIDERS).map(([key, p]) => (
                  <button key={key} onClick={() => applyProvider(key)} style={{
                    flex: 1, padding: "8px 10px", borderRadius: "var(--radius-sm)",
                    fontSize: 12, fontWeight: 500,
                    background: provider === key ? "var(--fg)" : "var(--bg-2)",
                    color: provider === key ? "var(--surface)" : "var(--fg-2)",
                    border: `1px solid ${provider === key ? "var(--fg)" : "var(--border-soft)"}`,
                    transition: "all .15s",
                  }}>{p.label}</button>
                ))}
              </div>

              <Toggle full
                      options={[{ value: "slab", label: "Slab tiers" }, { value: "flat", label: "Flat rate" }]}
                      value={rate.mode}
                      onChange={(v) => setRate((r) => ({ ...r, mode: v }))} />

              {rate.mode === "flat" ? (
                <div style={{ marginTop: 14 }}>
                  <NumberField large prefix={tweaks.currencySymbol} suffix="/m³"
                               value={rate.flat} min={0} step={10}
                               onChange={(v) => setRate((r) => ({ ...r, flat: Number(v) || 0 }))} />
                </div>
              ) : (
                <GasSlabEditor slabs={rate.slabs}
                               onUpdate={(slabs) => setRate((r) => ({ ...r, slabs }))}
                               currentM3={result.totalM3} />
              )}
            </Section>

            <Section title="Fixed charges" hint="Monthly meter rent, GIDC, etc.">
              <NumberField large prefix={tweaks.currencySymbol} suffix="/mo"
                           value={fixedCharges} min={0} step={50}
                           onChange={(v) => setFixedCharges(Number(v) || 0)} />
            </Section>
          </div>

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

            {appliances.length > 0 && (
              <Section title="Where the bill goes"
                       hint="Estimated per appliance based on usage">
                <div style={{ marginTop: 4 }}>
                  {[...result.perApp]
                    .sort((a, b) => b.m3 - a.m3)
                    .map((a) => (
                      <GasBreakdownRow key={a.id} a={a} totalM3={result.totalM3}
                                       currency={tweaks.currencySymbol} />
                    ))}
                </div>
                <GasBreakdownTotal result={result} 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: 'gas' });
                      const txt = `My gas bill estimate: ${fmtUnits(result.totalM3)} m³/mo, ${tweaks.currencySymbol} ${fmtPKR(result.totalBill, {symbol:""}).trim()}/mo | Pak Bill Calculator`;
                      if (navigator.share) { navigator.share({ title: "My gas bill estimate", text: txt }).catch(() => {}); }
                      else if (navigator.clipboard) { navigator.clipboard.writeText(txt); }
                    }}>
                    Share my estimate
                  </PrimaryButton>
                </div>
              </Section>
            )}

            {/* Protected status card */}
            {appliances.length > 0 && (
              <Section style={{ borderBottom: "none" }}>
                <div style={{
                  padding: 18, borderRadius: "var(--radius-lg)",
                  background: result.isProtected
                    ? "linear-gradient(135deg, var(--solar-soft), var(--surface) 70%)"
                    : "linear-gradient(135deg, oklch(0.97 0.02 28), var(--surface) 70%)",
                  border: `1px solid ${result.isProtected ? "var(--border-soft)" : "oklch(0.88 0.04 28)"}`,
                  display: "flex", flexDirection: "column", gap: 10,
                }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
                    <div style={{
                      width: 36, height: 36, borderRadius: 999, flexShrink: 0,
                      background: result.isProtected ? "var(--solar)" : "oklch(0.55 0.16 28)",
                      color: "white", display: "grid", placeItems: "center",
                      fontSize: 18,
                    }}>
                      {result.isProtected ? "✓" : "!"}
                    </div>
                    <div>
                      <div style={{ fontSize: 14, fontWeight: 600, color: "var(--fg)" }}>
                        {result.isProtected ? "Protected consumer" : "Non-protected consumer"}
                      </div>
                      <div style={{ fontSize: 12, color: "var(--muted)", marginTop: 2 }}>
                        {result.isProtected
                          ? `${fmtUnits(result.totalM3)} m³/mo, under the 90 m³ threshold`
                          : `${fmtUnits(result.totalM3)} m³/mo, exceeds the 90 m³ threshold`}
                      </div>
                    </div>
                  </div>
                  {tweaks.showTips && (
                    <div style={{ fontSize: 12, color: "var(--muted)", paddingTop: 4, borderTop: "1px solid var(--border-soft)" }}>
                      {result.isProtected
                        ? "SNGPL/SSGC protected consumers pay lower slab rates on the first 90 m³."
                        : "Usage above 90 m³ falls in the non-protected tier with higher rates."}
                    </div>
                  )}
                </div>
              </Section>
            )}
          </div>
        </div>
      </div>

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

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

function GasHero({ result, currency, count }) {
  const { totalM3, totalBill, variableCost, fixedCost, slabTier, isProtected } = result;
  const slabLabel = slabTier !== null ? `Slab ${slabTier + 1}` : "Flat rate";

  return (
    <div className="hero-row">
      <div>
        <div style={{ ...ss.label, marginBottom: 8 }}>Estimated gas 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" }}>
            {totalBill ? fmtPKR(totalBill, { symbol: "" }).trim() : "0"}
          </span>
        </div>
        <div style={{ display: "flex", gap: 6, marginTop: 16, flexWrap: "wrap" }}>
          <Pill tone="accent">
            <span className="mono">{fmtUnits(totalM3)}</span>&nbsp;m³/mo
          </Pill>
          <Pill>{slabLabel}</Pill>
          <Pill tone={isProtected ? "solar" : "ghost"}>
            {isProtected ? "Protected" : "Non-protected"}
          </Pill>
          <Pill tone="ghost">
            {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,
        }}>
          {totalBill > 0
            ? <>{currency}&nbsp;{fmtPKR(variableCost, { symbol: "" }).trim()} usage + {currency}&nbsp;{fmtPKR(fixedCost, { symbol: "" }).trim()} fixed charges.</>
            : <>Add a gas appliance to see your estimate.</>}
        </div>
      </div>

      {/* Right side stat card */}
      <div style={{
        display: "flex", flexDirection: "column", gap: 14,
        padding: 20,
        background: "var(--surface)",
        borderRadius: "var(--radius-lg)",
        border: "1px solid var(--border-soft)",
        boxShadow: "var(--shadow)",
      }}>
        <div>
          <div className="mono" style={{ fontSize: 10, color: "var(--muted)",
                                          textTransform: "uppercase", letterSpacing: "0.08em" }}>
            Monthly breakdown
          </div>
        </div>
        {[
          { label: "Usage charges", value: fmtPKR(variableCost, { symbol: currency }) },
          { label: "Fixed charges",  value: fmtPKR(fixedCost,    { symbol: currency }) },
          { label: "Total m³",       value: `${fmtUnits(totalM3)} m³` },
        ].map(({ label, value }) => (
          <div key={label} style={{
            display: "flex", justifyContent: "space-between", alignItems: "baseline",
            paddingBottom: 10, borderBottom: "1px dashed var(--border-soft)",
          }}>
            <span style={{ fontSize: 13, color: "var(--fg-2)" }}>{label}</span>
            <span className="mono" style={{ fontSize: 14, fontWeight: 600, color: "var(--fg)" }}>{value}</span>
          </div>
        ))}
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
          <span style={{ fontSize: 13, fontWeight: 600, color: "var(--fg)" }}>Total</span>
          <span className="mono" style={{ fontSize: 18, fontWeight: 600, color: "var(--fg)" }}>
            {fmtPKR(totalBill, { symbol: currency })}
          </span>
        </div>
      </div>
    </div>
  );
}

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

function GasEmptyState({ 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 burning yet.
      </div>
      <div style={{ fontSize: 13, color: "var(--muted)", marginTop: 6, marginBottom: 14 }}>
        Add your stove, geyser or room heater to estimate the gas bill.
      </div>
      <PrimaryButton onClick={onAdd} icon={<IconPlus size={14} stroke={2}/>}>
        Add appliance
      </PrimaryButton>
    </div>
  );
}

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

function GasApplianceCard({ a, totalM3, currency, compact, onEdit, onDelete }) {
  const catColors = {
    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)" },
    Heating:  { bg: "oklch(0.93 0.05 28)",  fg: "oklch(0.4 0.12 28)" },
    Laundry:  { bg: "oklch(0.93 0.04 280)", fg: "oklch(0.4 0.1 280)" },
    Other:    { bg: "var(--bg-2)", fg: "var(--muted)" },
  };
  const c = catColors[a.category] || catColors.Other;

  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 }}>
        {/* Category glyph */}
        <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",
        }}>{(a.category || "OT").slice(0,2).toUpperCase()}</div>

        <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 }}>
            {a.monthsPerYear < 12 ? `${a.monthsPerYear} mo/yr · ` : ""}{a.hoursPerDay}h/day · {a.consumptionM3PerHour} m³/h
          </div>
        </div>

        <div style={{ textAlign: "right" }}>
          <div className="mono" style={{ fontSize: 15, fontWeight: 600, color: "var(--fg)" }}>
            {fmtPKR(a.cost, { symbol: currency })}
          </div>
          <div className="mono" style={{ fontSize: 11, color: "var(--muted)" }}>
            {fmtUnits(a.m3)} m³
          </div>
        </div>
      </div>

      {!compact && (
        <div style={{ display: "flex", gap: 8, marginTop: 12, alignItems: "center" }}>
          <div style={{ flex: 1, height: 4, borderRadius: 999, background: "var(--bg-2)", overflow: "hidden" }}>
            <div style={{ width: `${Math.min(100, a.pct)}%`, height: "100%",
                          background: "var(--accent)", transition: "width .3s" }}/>
          </div>
          <span className="mono" style={{ fontSize: 11, color: "var(--muted)", width: 32, textAlign: "right" }}>
            {a.pct.toFixed(0)}%
          </span>
          <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>
  );
}

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

function GasSlabEditor({ slabs, onUpdate, currentM3 }) {
  const update = (i, val) => {
    onUpdate(slabs.map((s, j) => j === i ? { ...s, rate: Number(val) || 0 } : s));
  };
  return (
    <div style={{ marginTop: 14, display: "flex", flexDirection: "column", gap: 8 }}>
      {slabs.map((s, i) => {
        const active = currentM3 > s.fromM3;
        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 }}>
                {s.fromM3}{s.toM3 === null ? "+" : `–${s.toM3}`} m³
              </div>
            </div>
            <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
              <input type="number" value={s.rate} step={10} min={0}
                     onChange={(e) => update(i, e.target.value)}
                     className="mono"
                     style={{
                       width: 70, 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)" }}>/m³</span>
            </div>
          </div>
        );
      })}
    </div>
  );
}

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

function GasBreakdownRow({ a, totalM3, currency }) {
  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}
          {a.monthsPerYear < 12 && (
            <span style={{ fontSize: 11, color: "var(--muted)", marginLeft: 6 }}>({a.monthsPerYear}mo/yr)</span>
          )}
        </div>
        <div className="mono" style={{ fontSize: 13, fontWeight: 500, color: "var(--fg)", flexShrink: 0 }}>
          {fmtPKR(a.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, a.pct)}%`, height: "100%", background: "var(--fg-2)" }}/>
        </div>
        <div className="mono" style={{ fontSize: 11, color: "var(--muted)", width: 38, textAlign: "right" }}>
          {a.pct.toFixed(0)}%
        </div>
      </div>
    </div>
  );
}

function GasBreakdownTotal({ result, currency }) {
  const { totalM3, variableCost, fixedCost, totalBill } = result;
  return (
    <div style={{ marginTop: 12, paddingTop: 12, borderTop: "1px solid var(--border)" }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
        <div>
          <div style={{ fontSize: 13, fontWeight: 600 }}>Variable total</div>
          <div className="mono" style={{ fontSize: 11, color: "var(--muted)" }}>
            {fmtUnits(totalM3)} m³ consumed
          </div>
        </div>
        <div className="mono" style={{ fontSize: 16, fontWeight: 600, color: "var(--fg)" }}>
          {fmtPKR(variableCost, { symbol: currency })}
        </div>
      </div>
      <div style={{
        display: "flex", justifyContent: "space-between", alignItems: "baseline",
        marginTop: 8, paddingTop: 8, borderTop: "1px dashed var(--border-soft)",
      }}>
        <div style={{ fontSize: 13, color: "var(--fg-2)" }}>Fixed charges</div>
        <div className="mono" style={{ fontSize: 14, color: "var(--fg-2)" }}>
          {fmtPKR(fixedCost, { symbol: currency })}
        </div>
      </div>
      <div style={{
        display: "flex", justifyContent: "space-between", alignItems: "baseline",
        marginTop: 8, paddingTop: 8, borderTop: "1px solid var(--border)",
      }}>
        <div style={{ fontSize: 14, fontWeight: 700 }}>Grand total</div>
        <div className="mono" style={{ fontSize: 22, fontWeight: 700, color: "var(--fg)" }}>
          {fmtPKR(totalBill, { symbol: currency })}
        </div>
      </div>
    </div>
  );
}

// ---- Add / Edit form -------------------------------------------------------

function GasApplianceForm({ editing, onSave, onDelete }) {
  const [mode, setMode] = React.useState(editing ? "manual" : "search");
  const [query, setQuery] = React.useState("");
  const [draft, setDraft] = React.useState(editing || {
    id: `g${Date.now()}`,
    type: "", category: "Kitchen",
    consumptionM3PerHour: 0.45,
    hoursPerDay: 2,
    monthsPerYear: 12,
  });

  const matches = React.useMemo(() => {
    if (!query.trim()) return GAS_APPLIANCE_CATALOG.slice(0, 8);
    const q = query.toLowerCase();
    return GAS_APPLIANCE_CATALOG.filter((a) => a.type.toLowerCase().includes(q));
  }, [query]);

  const pickFromCatalog = (a) => {
    setDraft({
      ...draft,
      type: a.type,
      category: a.category,
      consumptionM3PerHour: a.consumptionM3PerHour,
      hoursPerDay: a.defaultHours,
      monthsPerYear: a.defaultMonths,
    });
    setMode("manual");
  };

  // Live preview
  const m3Preview = draft.consumptionM3PerHour * draft.hoursPerDay * 30 * (draft.monthsPerYear / 12);
  const canSave = draft.type.trim().length > 0 && draft.consumptionM3PerHour > 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 stove, geyser, heater…"
                   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={() => pickFromCatalog(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.consumptionM3PerHour} m³/h</div>
                </div>
                <div style={{ fontSize: 12, color: "var(--muted)" }}>
                  {a.category} · {a.defaultHours}h/day{a.defaultMonths < 12 ? ` · ${a.defaultMonths} mo/yr` : ""}
                </div>
              </button>
            ))}
          </div>
        </>
      )}

      {mode === "manual" && (
        <>
          <label style={{ display: "flex", flexDirection: "column", gap: 6 }}>
            <span style={ss.label}>Appliance name</span>
            <input value={draft.type}
                   onChange={(e) => setDraft({ ...draft, type: e.target.value })}
                   placeholder="e.g. Gas Geyser" style={ss.input}/>
          </label>

          <label style={{ display: "flex", flexDirection: "column", gap: 6 }}>
            <span style={ss.label}>Category</span>
            <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
              {GAS_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>
          </label>

          <label style={{ display: "flex", flexDirection: "column", gap: 6 }}>
            <span style={ss.label}>Consumption rate</span>
            <NumberField suffix="m³/hour" mono value={draft.consumptionM3PerHour} min={0.01} step={0.05}
                         onChange={(v) => setDraft({ ...draft, consumptionM3PerHour: Number(v) || 0 })}/>
          </label>

          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
            <label style={{ display: "flex", flexDirection: "column", gap: 6 }}>
              <span style={ss.label}>Hours per day</span>
              <NumberField suffix="h" mono value={draft.hoursPerDay} min={0.1} step={0.25}
                           onChange={(v) => setDraft({ ...draft, hoursPerDay: Number(v) || 0 })}/>
            </label>
            <label style={{ display: "flex", flexDirection: "column", gap: 6 }}>
              <span style={ss.label}>Months per year</span>
              <NumberField suffix="mo" mono value={draft.monthsPerYear} min={1} max={12} step={1}
                           onChange={(v) => setDraft({ ...draft, monthsPerYear: Math.min(12, Math.max(1, Number(v) || 12)) })}/>
            </label>
          </div>

          {/* Live preview */}
          <div style={{
            padding: 14, borderRadius: "var(--radius)",
            background: "var(--bg-2)", border: "1px solid var(--border-soft)",
            display: "flex", justifyContent: "space-between", alignItems: "center",
          }}>
            <div>
              <div className="mono" style={{ fontSize: 10, color: "var(--muted)", textTransform: "uppercase", letterSpacing: "0.06em" }}>Monthly avg</div>
              <div style={{ fontSize: 12, color: "var(--muted)", marginTop: 2 }}>
                {draft.monthsPerYear < 12 ? `${draft.monthsPerYear} active months amortised over 12` : "Used all year"}
              </div>
            </div>
            <div style={{ textAlign: "right" }}>
              <span className="mono" style={{ fontSize: 28, fontWeight: 600, color: "var(--fg)" }}>{fmtUnits(m3Preview)}</span>
              <span style={{ fontSize: 13, color: "var(--muted)", marginLeft: 4 }}>m³/mo</span>
            </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>
  );
}

Object.assign(window, { GasBill });
