// app.jsx — main dashboard. Pure math comes from calc.js (window.*); React/UI lives here.

const {
  classifyInterval,
  buildIndex,
  peakHourStats,
  peakDayInRange,
  fillDayIntervals,
  aggregateByCategory,
  computeCost,
  computeSavings,
  DEFAULT_TARIFF_NIS_PER_KWH,
  TARIFF_SLIDER_MIN_AGOROT,
  TARIFF_SLIDER_MAX_AGOROT,
  TOU,
  DISCOUNT_TIERS,
  fmtTouRange,
} = window;

const DAY_BAND_LABEL   = `${fmtTouRange(TOU.DAY_START_HOUR, TOU.DAY_END_HOUR)} א'–ה'`;
const NIGHT_BAND_LABEL = `${fmtTouRange(TOU.NIGHT_START_HOUR, TOU.NIGHT_END_HOUR)} א'–ה'`;

const TWEAK_DEFAULTS = {
  tariff: DEFAULT_TARIFF_NIS_PER_KWH,
  showCost: true,
  accent: 'warm',
};

const ACCENT_PRESETS = {
  warm:  { accent: 'oklch(0.72 0.16 50)',  soft: 'oklch(0.94 0.05 60)',  ink: 'oklch(0.4 0.14 45)',  hi1: 'oklch(0.78 0.14 70)' },
  cool:  { accent: 'oklch(0.66 0.13 230)', soft: 'oklch(0.94 0.04 230)', ink: 'oklch(0.38 0.12 240)',hi1: 'oklch(0.74 0.12 215)' },
  green: { accent: 'oklch(0.66 0.13 155)', soft: 'oklch(0.94 0.045 155)',ink: 'oklch(0.36 0.12 155)',hi1: 'oklch(0.74 0.12 150)' },
};

const HEB_MONTHS = ['ינואר','פברואר','מרץ','אפריל','מאי','יוני','יולי','אוגוסט','ספטמבר','אוקטובר','נובמבר','דצמבר'];
const HEB_MONTHS_SHORT = ['ינו','פבר','מרץ','אפר','מאי','יונ','יול','אוג','ספט','אוק','נוב','דצמ'];
const HEB_DOW_SHORT = ['א','ב','ג','ד','ה','ו','ש'];

function fmtNum(v, digits = 1) {
  return v.toLocaleString('he-IL', { minimumFractionDigits: digits, maximumFractionDigits: digits });
}
function fmtCurrency(v) {
  return '₪' + v.toLocaleString('he-IL', { minimumFractionDigits: 0, maximumFractionDigits: 0 });
}
function fmtDate(d) {
  return `${d.getDate().toString().padStart(2,'0')}/${(d.getMonth()+1).toString().padStart(2,'0')}/${d.getFullYear()}`;
}
function fmtDateLong(d) {
  return `יום ${['ראשון','שני','שלישי','רביעי','חמישי','שישי','שבת'][d.getDay()]}, ${d.getDate()} ב${HEB_MONTHS[d.getMonth()]} ${d.getFullYear()}`;
}

const Icon = {
  bolt: (s = 16) => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M13 2L4.5 13.5h6L11 22l8.5-11.5h-6L13 2z"/></svg>,
  sun:  (s = 16) => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"/></svg>,
  moon: (s = 16) => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg>,
  cal:  (s = 16) => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="4" width="18" height="18" rx="3"/><path d="M16 2v4M8 2v4M3 10h18"/></svg>,
  trophy:(s = 16) => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M8 21h8M12 17v4M7 4h10v5a5 5 0 0 1-10 0V4zM7 4H4v3a3 3 0 0 0 3 3M17 4h3v3a3 3 0 0 1-3 3"/></svg>,
  spark:(s = 16) => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 3v3M5.6 5.6l2 2M3 12h3M5.6 18.4l2-2M12 18v3M16.4 16.4l2 2M18 12h3M16.4 7.6l2-2"/><circle cx="12" cy="12" r="3"/></svg>,
  arrowL:(s = 14) => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><polyline points="15 18 9 12 15 6"/></svg>,
  arrowR:(s = 14) => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><polyline points="9 18 15 12 9 6"/></svg>,
  refresh:(s = 14) => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/></svg>,
};

function App() {
  const [data, setData] = React.useState(null);
  const [fileName, setFileName] = React.useState(null);

  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  React.useEffect(() => {
    const p = ACCENT_PRESETS[t.accent] || ACCENT_PRESETS.warm;
    document.documentElement.style.setProperty('--accent', p.accent);
    document.documentElement.style.setProperty('--accent-soft', p.soft);
    document.documentElement.style.setProperty('--accent-ink', p.ink);
  }, [t.accent]);

  if (!data) {
    return (
      <UploadScreen
        onLoaded={(parsed, name) => { setData(parsed); setFileName(name); }}
        onDemo={() => { setData(window.makeSampleData()); setFileName('דמו'); }}
      />
    );
  }

  return <Dashboard data={data} fileName={fileName} tweak={t} setTweak={setTweak} onReset={() => setData(null)} />;
}

function Dashboard({ data, fileName, tweak, setTweak, onReset }) {
  const idx = React.useMemo(() => buildIndex(data.intervals), [data]);

  const [year, setYear] = React.useState(() => idx.years[idx.years.length - 1]);
  const [scope, setScope] = React.useState('year');
  const [month, setMonth] = React.useState(() => {
    const yi = data.intervals.filter(i => i.date.getFullYear() === idx.years[idx.years.length - 1]);
    return yi.length ? yi[yi.length - 1].date.getMonth() : new Date().getMonth();
  });
  const [day, setDay] = React.useState(() => {
    const yi = data.intervals.filter(i => i.date.getFullYear() === idx.years[idx.years.length - 1]);
    const d = yi.length ? yi[yi.length - 1].date : new Date();
    return new Date(d.getFullYear(), d.getMonth(), d.getDate());
  });

  const monthsInYear = React.useMemo(() => {
    const s = new Set();
    for (const it of data.intervals) if (it.date.getFullYear() === year) s.add(it.date.getMonth());
    return s;
  }, [data, year]);

  const daysInMonth = React.useMemo(() => {
    const s = new Set();
    for (const it of data.intervals) {
      if (it.date.getFullYear() === year && it.date.getMonth() === month) s.add(it.date.getDate());
    }
    return [...s].sort((a,b)=>a-b);
  }, [data, year, month]);

  React.useEffect(() => {
    if (!daysInMonth.length) return;
    if (day.getFullYear() !== year || day.getMonth() !== month || !daysInMonth.includes(day.getDate())) {
      const targetDay = daysInMonth[daysInMonth.length - 1];
      setDay(new Date(year, month, targetDay));
    }
  }, [year, month]); // eslint-disable-line

  const yearTotal = idx.yearTotals[year] || 0;
  const intervalsInYear = React.useMemo(
    () => data.intervals.filter(i => i.date.getFullYear() === year),
    [data, year]
  );
  const intervalsInMonth = React.useMemo(
    () => data.intervals.filter(i => i.date.getFullYear() === year && i.date.getMonth() === month),
    [data, year, month]
  );
  const dayKey = `${day.getFullYear()}-${day.getMonth()}-${day.getDate()}`;
  const intervalsInDay = idx.byDay[dayKey] || [];

  const activeIntervals = scope === 'year' ? intervalsInYear
                        : scope === 'month' ? intervalsInMonth
                        : intervalsInDay;
  const periodTotal = activeIntervals.reduce((s, i) => s + i.kwh, 0);

  const { day: dayRate, night: nightRate } = React.useMemo(
    () => aggregateByCategory(activeIntervals),
    [activeIntervals]
  );

  const chartData = React.useMemo(() => {
    if (scope === 'year') {
      return Array.from({ length: 12 }).map((_, m) => ({
        label: HEB_MONTHS_SHORT[m],
        value: idx.monthTotals[`${year}-${m}`] || 0,
        m,
      }));
    } else if (scope === 'month') {
      const daysCount = new Date(year, month + 1, 0).getDate();
      return Array.from({ length: daysCount }).map((_, di) => {
        const dd = di + 1;
        const val = idx.dayTotals[`${year}-${month}-${dd}`] || 0;
        return { label: String(dd), value: val, day: dd };
      });
    }
    return [];
  }, [scope, year, month, idx]);

  const peakHr = React.useMemo(() => peakHourStats(activeIntervals), [activeIntervals]);
  const peakDay = React.useMemo(() => peakDayInRange(activeIntervals), [activeIntervals]);
  const yearPeakDay = React.useMemo(() => peakDayInRange(intervalsInYear), [intervalsInYear]);

  const { day: yearDayKwh, night: yearNightKwh } = React.useMemo(
    () => aggregateByCategory(intervalsInYear),
    [intervalsInYear]
  );

  const periodTitle = scope === 'year' ? `שנת ${year}`
                    : scope === 'month' ? `${HEB_MONTHS[month]} ${year}`
                    : fmtDateLong(day);
  const periodLabel = scope === 'year' ? 'סך הכל השנה' : scope === 'month' ? 'סך הכל החודש' : 'סך הכל היום';

  const tariff = tweak.tariff;
  const showCost = tweak.showCost;
  const cost = computeCost(periodTotal, tariff);
  const yearCost = computeCost(yearTotal, tariff);

  return (
    <div className="app">
      <div className="topbar">
        <div className="brand">
          <div className="brand-glyph">{Icon.bolt(20)}</div>
          <div>
            <p className="brand-name">לוח החשמל שלי</p>
            <p className="brand-sub">{fileName}</p>
          </div>
        </div>
        <div className="topbar-actions">
          <div className="year-switch">
            {idx.years.map(y => (
              <button key={y} className={y === year ? 'on' : ''} onClick={() => setYear(y)}>{y}</button>
            ))}
          </div>
          <button className="muted-link" onClick={onReset} title="טען קובץ חדש">
            {Icon.refresh()}
            <span>קובץ חדש</span>
          </button>
        </div>
      </div>

      <div className="customer-card">
        <Field label="שם לקוח" value={data.customer.name} />
        <Field label="כתובת" value={data.customer.address} />
        <Field label="מספר חוזה" value={data.customer.contractId} />
        <Field label="מונה" value={`${data.customer.meterCode}-${data.customer.meterNumber}`} sub={data.customer.meterType} />
      </div>

      <div className="kpi-row">
        <div className="kpi featured">
          <div className="kpi-label">
            <span className="kpi-icon">{Icon.bolt(13)}</span>
            סך צריכה שנתית · {year}
          </div>
          <div className="kpi-value">{fmtNum(yearTotal, 0)} <span className="kpi-unit">קוט"ש</span></div>
          {showCost && <div className="kpi-sub">בעלות מוערכת של <strong>{fmtCurrency(yearCost)}</strong> לפי תעריף של <strong><span dir="ltr" style={{unicodeBidi:'isolate'}}>{(tariff*100).toFixed(2)}</span> אג'/קוט"ש</strong></div>}
        </div>

        <div className="kpi period">
          <div className="kpi-label">
            <span className="kpi-icon">{Icon.cal(13)}</span>
            {periodLabel}
          </div>
          <div className="kpi-value">{fmtNum(periodTotal, scope === 'day' ? 2 : 0)} <span className="kpi-unit">קוט"ש</span></div>
          {showCost && <div className="kpi-sub"><strong>{fmtCurrency(cost)}</strong> · {Math.round((periodTotal / Math.max(0.001, yearTotal)) * 100)}% מהשנה</div>}
        </div>

        <div className="kpi day">
          <div className="kpi-label">
            <span className="kpi-icon">{Icon.sun(13)}</span>
            תעריף יום · {DAY_BAND_LABEL}
          </div>
          <div className="kpi-value">{fmtNum(dayRate, scope === 'day' ? 2 : 0)} <span className="kpi-unit">קוט"ש</span></div>
          <div className="kpi-sub">{periodTotal > 0 ? Math.round((dayRate / periodTotal) * 100) : 0}% מהצריכה {showCost && <>· <strong>{fmtCurrency(computeCost(dayRate, tariff))}</strong></>}</div>
        </div>

        <div className="kpi night">
          <div className="kpi-label">
            <span className="kpi-icon">{Icon.moon(13)}</span>
            תעריף לילה · {NIGHT_BAND_LABEL}
          </div>
          <div className="kpi-value">{fmtNum(nightRate, scope === 'day' ? 2 : 0)} <span className="kpi-unit">קוט"ש</span></div>
          <div className="kpi-sub">{periodTotal > 0 ? Math.round((nightRate / periodTotal) * 100) : 0}% מהצריכה {showCost && <>· <strong>{fmtCurrency(computeCost(nightRate, tariff))}</strong></>}</div>
        </div>
      </div>

      <div className="period-panel">
        <div className="period-head">
          <div>
            <h2 className="period-title"><small>היסטוריית צריכה ·</small> {periodTitle}</h2>
          </div>
          <div className="scope-switch" role="tablist">
            <button className={scope === 'year' ? 'on' : ''} onClick={() => setScope('year')}>שנה</button>
            <button className={scope === 'month' ? 'on' : ''} onClick={() => setScope('month')}>חודש</button>
            <button className={scope === 'day' ? 'on' : ''} onClick={() => setScope('day')}>יום</button>
          </div>
        </div>

        {(scope === 'month' || scope === 'day') && (
          <div className="nav-row" style={{marginBottom:18}}>
            <div className="month-chips">
              {HEB_MONTHS_SHORT.map((mn, mi) => (
                <button
                  key={mi}
                  className={mi === month ? 'on' : ''}
                  disabled={!monthsInYear.has(mi)}
                  onClick={() => setMonth(mi)}
                >{mn}</button>
              ))}
            </div>
            {scope === 'day' && (function() {
              const minD = data.intervals[0].date;
              const maxD = data.intervals[data.intervals.length - 1].date;
              const fmtISO = (d) => `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`;
              const minISO = fmtISO(new Date(minD.getFullYear(), minD.getMonth(), minD.getDate()));
              const maxISO = fmtISO(new Date(maxD.getFullYear(), maxD.getMonth(), maxD.getDate()));
              const goRel = (delta) => {
                const candidates = data.intervals
                  .map(i => new Date(i.date.getFullYear(), i.date.getMonth(), i.date.getDate()))
                  .filter(d => delta < 0 ? d < day : d > day);
                if (!candidates.length) return;
                const pick = delta < 0
                  ? new Date(Math.max(...candidates.map(d => d.getTime())))
                  : new Date(Math.min(...candidates.map(d => d.getTime())));
                setDay(pick); setYear(pick.getFullYear()); setMonth(pick.getMonth());
              };
              return (
                <div className="day-picker">
                  <span className="lbl">יום:</span>
                  <input
                    type="date"
                    className="day-input"
                    value={fmtISO(day)}
                    min={minISO}
                    max={maxISO}
                    onChange={(e) => {
                      const v = e.target.value;
                      if (!v) return;
                      const [yy, mm, dd] = v.split('-').map(Number);
                      const nd = new Date(yy, mm - 1, dd);
                      setDay(nd); setYear(yy); setMonth(mm - 1);
                    }}
                  />
                  <div className="arrows">
                    <button onClick={() => goRel(-1)} title="יום קודם">{Icon.arrowR(14)}</button>
                    <button onClick={() => goRel(1)} title="יום הבא">{Icon.arrowL(14)}</button>
                  </div>
                </div>
              );
            })()}
          </div>
        )}

        {scope === 'year' && (
          <BarChart
            data={chartData}
            activeIndex={null}
            onSelect={(i) => { setMonth(i); setScope('month'); }}
            formatLabel={(d) => d.label}
          />
        )}
        {scope === 'month' && (
          <BarChart
            data={chartData}
            activeIndex={daysInMonth.includes(day.getDate()) && day.getMonth() === month ? day.getDate() - 1 : null}
            onSelect={(i) => { setDay(new Date(year, month, i + 1)); setScope('day'); }}
            formatLabel={(d, i) => {
              const daysCount = chartData.length;
              const step = daysCount > 15 ? 3 : 1;
              return (i + 1) % step === 0 || i === 0 || i === daysCount - 1 ? d.label : '';
            }}
            formatTip={(d) => ({ label: fmtDate(new Date(year, month, d.day)) })}
          />
        )}
        {scope === 'day' && (
          <DayChart intervals={fillDayIntervals(intervalsInDay, day)} dayDate={day} />
        )}

        {scope === 'day' && (
          <div style={{marginTop:14, display:'flex', gap:18, fontSize:12.5, color:'var(--ink-dim)'}}>
            <LegendDot color="var(--day)" label={<>{fmtTouRange(TOU.DAY_START_HOUR, TOU.DAY_END_HOUR)} (תעריף יום, א'–ה')</>} />
            <LegendDot color="var(--night)" label={<>{fmtTouRange(TOU.NIGHT_START_HOUR, TOU.NIGHT_END_HOUR)} (תעריף לילה, א'–ה')</>} />
          </div>
        )}
      </div>

      <div className="insights-row">
        <Insight
          icon={Icon.spark(13)}
          label={scope === 'day' ? 'שעת שיא ביום זה' : 'שעת השיא בתקופה'}
          value={peakHr ? `${peakHr.hour.toString().padStart(2,'0')}:00–${((peakHr.hour+1)%24).toString().padStart(2,'0')}:00` : '—'}
          meta={peakHr ? <>צריכה כוללת של <strong>{fmtNum(peakHr.total, 1)} קוט"ש</strong> בשעה זו</> : null}
        />
        <Insight
          icon={Icon.trophy(13)}
          label={scope === 'day' ? 'שיא רבע-שעה' : 'יום השיא בתקופה'}
          value={scope === 'day'
            ? (function() {
                if (!intervalsInDay.length) return '—';
                let best = intervalsInDay[0];
                for (const it of intervalsInDay) if (it.kwh > best.kwh) best = it;
                return `${best.date.getHours().toString().padStart(2,'0')}:${best.date.getMinutes().toString().padStart(2,'0')}`;
              })()
            : peakDay ? fmtDate(peakDay.date) : '—'}
          meta={scope === 'day'
            ? (function() {
                if (!intervalsInDay.length) return null;
                let best = intervalsInDay[0];
                for (const it of intervalsInDay) if (it.kwh > best.kwh) best = it;
                return <><strong>{best.kwh.toFixed(3)} קוט"ש</strong> ברבע-שעה זו</>;
              })()
            : peakDay ? <><strong>{fmtNum(peakDay.total, 1)} קוט"ש</strong> · {['ראשון','שני','שלישי','רביעי','חמישי','שישי','שבת'][peakDay.date.getDay()]}</> : null}
          showBar={scope !== 'day' && peakDay}
          barPct={peakDay && periodTotal > 0 ? Math.min(100, (peakDay.total / Math.max(...activeIntervals.map(i=>i.kwh)) * 100) || 0) : 0}
        />
        <Insight
          icon={Icon.trophy(13)}
          label={`יום השיא ב-${year}`}
          value={yearPeakDay ? fmtDate(yearPeakDay.date) : '—'}
          meta={yearPeakDay ? <><strong>{fmtNum(yearPeakDay.total, 1)} קוט"ש</strong> · {['ראשון','שני','שלישי','רביעי','חמישי','שישי','שבת'][yearPeakDay.date.getDay()]}</> : null}
        />
      </div>

      <SavingsPanel
        year={year}
        yearKwh={yearTotal}
        yearDayKwh={yearDayKwh}
        yearNightKwh={yearNightKwh}
        tariff={tariff}
      />

      <TweaksPanel>
        <TweakSection label="מראה" />
        <TweakRadio
          label="גוון"
          value={tweak.accent}
          options={[{value:'warm', label:'חמים'}, {value:'cool', label:'קר'}, {value:'green', label:'ירוק'}]}
          onChange={(v) => setTweak('accent', v)}
        />
        <TweakSection label="חישוב עלות" />
        <TweakToggle
          label="הצג עלות"
          value={tweak.showCost}
          onChange={(v) => setTweak('showCost', v)}
        />
        <TweakSlider
          label="תעריף"
          value={Math.round(tweak.tariff * 10000) / 100}
          min={TARIFF_SLIDER_MIN_AGOROT}
          max={TARIFF_SLIDER_MAX_AGOROT}
          step={0.01}
          unit=" אג'/kWh"
          onChange={(v) => setTweak('tariff', Math.round(v * 100) / 10000)}
        />
      </TweaksPanel>
    </div>
  );
}

function Field({ label, value, sub }) {
  return (
    <div className="cust-field">
      <span className="cust-label">{label}</span>
      <span className="cust-value" title={value}>{value}</span>
      {sub && <span style={{fontSize:11.5, color:'var(--ink-faint)'}}>{sub}</span>}
    </div>
  );
}

function Insight({ icon, label, value, meta, showBar, barPct }) {
  return (
    <div className="insight">
      <div className="insight-label">
        <span style={{width:22, height:22, borderRadius:7, display:'grid', placeItems:'center', background:'var(--accent-soft)', color:'var(--accent-ink)'}}>{icon}</span>
        {label}
      </div>
      <div className="insight-value">{value}</div>
      <div className="insight-meta">{meta}</div>
      {showBar && <div className="insight-bar"><span style={{width:`${Math.max(8, barPct)}%`}} /></div>}
    </div>
  );
}

function LegendDot({ color, label }) {
  return (
    <span style={{display:'inline-flex', alignItems:'center', gap:6}}>
      <span style={{width:10, height:10, borderRadius:3, background:color, display:'inline-block'}} />
      <span>{label}</span>
    </span>
  );
}

function SavingsPanel({ year, yearKwh, yearDayKwh, yearNightKwh, tariff }) {
  const yearCost = computeCost(yearKwh, tariff);

  return (
    <section className="savings-panel">
      <header className="savings-head">
        <div>
          <h2 className="savings-title">פוטנציאל חיסכון שנתי</h2>
          <p className="savings-sub">אחוזי הנחה נפוצים שספקי חשמל פרטיים מציעים על התעריף הרגולטורי. כל אחוז למטה מציג את החיסכון הפוטנציאלי השנתי על בסיס הצריכה שלך ב-{year}.</p>
        </div>
        <div className="savings-baseline">
          <span>חשבון שנתי נוכחי</span>
          <strong>{fmtCurrency(yearCost)}</strong>
          <em>{fmtNum(yearKwh, 0)} קוט"ש · <span dir="ltr" style={{unicodeBidi:'isolate'}}>{(tariff*100).toFixed(2)}</span> אג'/קוט"ש</em>
        </div>
      </header>

      <div className="savings-grid">
        <SavingsCard
          accent="warm"
          icon={Icon.bolt(13)}
          title="הנחה אחידה על תעריף מלא"
          subtitle="הנחה זהה על כל שעות הצריכה"
          totalCost={yearCost}
          discountedKwh={yearKwh}
          totalKwh={yearKwh}
          tariff={tariff}
          tiers={DISCOUNT_TIERS.flat}
        />
        <SavingsCard
          accent="day"
          icon={Icon.sun(13)}
          title="הנחה על תעריף יום"
          subtitle={<>{fmtTouRange(TOU.DAY_START_HOUR, TOU.DAY_END_HOUR)} · א'–ה'</>}
          totalCost={yearCost}
          discountedKwh={yearDayKwh}
          totalKwh={yearKwh}
          tariff={tariff}
          tiers={DISCOUNT_TIERS.day}
        />
        <SavingsCard
          accent="night"
          icon={Icon.moon(13)}
          title="הנחה על תעריף לילה"
          subtitle={<>{fmtTouRange(TOU.NIGHT_START_HOUR, TOU.NIGHT_END_HOUR)} · א'–ה'</>}
          totalCost={yearCost}
          discountedKwh={yearNightKwh}
          totalKwh={yearKwh}
          tariff={tariff}
          tiers={DISCOUNT_TIERS.night}
        />
      </div>

      <p className="savings-disclaimer">
        <strong>שימו לב:</strong> הסכומים מהווים הערכה בלבד ומבוססים על אחוזי הנחה נפוצים אצל ספקי חשמל פרטיים שונים. ההצעות בפועל משתנות מספק לספק, עשויות לכלול תנאים נלווים (תשלום חודשי, מינימום צריכה, תקופת התחייבות) ומשתנות מעת לעת. מומלץ לבדוק ולהשוות את ההצעות העדכניות מספקים שונים לפני קבלת החלטה.
      </p>
    </section>
  );
}

function SavingsCard({ accent, icon, title, subtitle, totalCost, discountedKwh, totalKwh, tariff, tiers }) {
  const scopePct = totalKwh > 0 ? Math.round((discountedKwh / totalKwh) * 100) : 0;
  return (
    <div className={`savings-card savings-${accent}`}>
      <div className="savings-card-head">
        <span className="savings-icon">{icon}</span>
        <div>
          <h3>{title}</h3>
          <p>{subtitle}</p>
        </div>
      </div>
      <div className="savings-card-base">
        חלה על <strong>{fmtNum(discountedKwh, 0)} קוט"ש</strong> מתוך {fmtNum(totalKwh, 0)} (<span dir="ltr" style={{unicodeBidi:'isolate'}}>{scopePct}%</span> מהשנה)
      </div>
      <div className="savings-tiers">
        {tiers.map(pct => {
          const { savings, netCost } = computeSavings({ discountedKwh, totalCost, tariff, pct });
          return (
            <div key={pct} className="tier">
              <span className="tier-pct"><span dir="ltr" style={{unicodeBidi:'isolate'}}>{pct}%</span></span>
              <div className="tier-info">
                <span className="tier-label">חיסכון פוטנציאלי</span>
                <span className="tier-savings"><bdi dir="ltr">{`-${fmtNum(savings, 0)}₪`}</bdi></span>
                <span className="tier-net">חשבון שנתי לאחר הנחה: <strong>{fmtCurrency(netCost)}</strong></span>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
