/* ============================================================
   Lima Android — Rain Alerts screen (MET Norway forecast)
   ============================================================ */
const RAIN_SAMPLE = (prov) => {
  const rnd = seedRand('alerts' + prov);
  const today = new Date();
  const base = D.provinces.find(p => p.name === prov).avg_rainfall_mm / 1000;
  const daily = [];
  for (let i = 0; i < 9; i++) {
    const d = new Date(today); d.setDate(today.getDate() + i);
    let mm = Math.round(rnd() * 30 * base * (i === 3 || i === 4 ? 2.4 : 1) * 10) / 10;
    if (i >= 6) mm = Math.round(rnd() * 1.5 * 10) / 10;
    daily.push({ date: d.toISOString().slice(0, 10), rain_mm: mm, complete: i < 8 });
  }
  const th = { watchMm: 20, warningMm: 40, dryDayMm: 1, drySpellDays: 5 };
  const alerts = [];
  const heavy = daily.filter(d => d.rain_mm >= th.watchMm);
  if (heavy.length) {
    const peak = heavy.reduce((a, b) => b.rain_mm > a.rain_mm ? b : a);
    alerts.push({ type: 'heavy_rain', level: peak.rain_mm >= th.warningMm ? 'warning' : 'watch', from: heavy[0].date, to: heavy[heavy.length - 1].date, rain_mm: peak.rain_mm,
      title: peak.rain_mm >= th.warningMm ? 'Heavy rain expected' : 'Heavy rain possible',
      advice: 'Delay fertiliser top-dressing and spraying until after the rain. Clear drainage furrows so fields do not waterlog. Cover harvested produce.' });
  }
  if (daily.slice(-4).every(d => d.rain_mm < th.dryDayMm)) alerts.push({ type: 'dry_spell', level: 'info', from: daily[daily.length - 4].date, to: daily[daily.length - 1].date, rain_mm: 0,
    title: 'Dry spell starting', advice: 'Little or no rain for the last days of the forecast. Plan supplementary irrigation for seedlings and mulch to hold soil moisture.' });
  const upd = new Date(today); upd.setHours(today.getHours() - 3);
  return { province: prov, source: 'MET Norway', attribution: 'Forecast data from MET Norway, CC BY 4.0', updatedAt: upd.toISOString(), stale: false, thresholds: th, daily, alerts,
    disclaimer: 'Automated forecast-based alert, not an official weather warning. Check official sources before critical field operations.',
    officialSources: [{ name: 'Zambia Meteorological Department', url: 'http://www.zmd.gov.zm' }, { name: 'DMMU' }] };
};
const rDay = (iso, opt = { weekday: 'short' }) => new Date(iso + 'T00:00:00').toLocaleDateString('en-ZM', opt);
const rRange = (a, b) => a === b ? rDay(a, { weekday: 'short', day: 'numeric', month: 'short' }) : `${rDay(a, { weekday: 'short', day: 'numeric' })} – ${rDay(b, { weekday: 'short', day: 'numeric', month: 'short' })}`;
const rUpdated = iso => new Date(iso).toLocaleString('en-ZM', { day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit' });
const RLEVEL = {
  warning: { c: 'var(--clay)', bg: 'rgba(178,58,46,.08)', bd: 'rgba(178,58,46,.3)', t: 'Warning', tone: 'clay' },
  watch: { c: 'var(--gold-d)', bg: 'rgba(201,151,43,.09)', bd: 'rgba(201,151,43,.35)', t: 'Watch', tone: 'gold' },
  info: { c: 'var(--navy)', bg: 'rgba(27,58,107,.06)', bd: 'rgba(27,58,107,.22)', t: 'Info', tone: 'navy' },
};

function RainChartM({ daily, thresholds, W = 344 }) {
  const H = 190, padL = 30, padR = 8, padT = 16, padB = 32;
  const max = Math.max(thresholds.warningMm * 1.15, ...daily.map(d => d.rain_mm)) || 1;
  const iw = W - padL - padR, ih = H - padT - padB, bw = iw / daily.length;
  const y = v => padT + ih - (v / max) * ih;
  const Ref = ({ v, color, label }) => <g>
    <line x1={padL} x2={W - padR} y1={y(v)} y2={y(v)} stroke={color} strokeWidth="1.5" strokeDasharray="4 4" />
    <text x={W - padR} y={y(v) - 4} textAnchor="end" fontSize="10" fontWeight="700" fill={color} fontFamily="'DM Mono',monospace">{label} {v}</text>
  </g>;
  return <svg width={W} height={H} style={{ display: 'block' }} role="img" aria-label="Daily rainfall forecast">
    {[0, 0.5, 1].map(f => <g key={f}><line x1={padL} x2={W - padR} y1={y(max * f)} y2={y(max * f)} stroke="var(--line)" />
      <text x={padL - 6} y={y(max * f) + 3.5} textAnchor="end" fontSize="10" fill="var(--ink-faint)" fontFamily="'DM Mono',monospace">{Math.round(max * f)}</text></g>)}
    <Ref v={thresholds.watchMm} color="var(--gold)" label="Watch" />
    <Ref v={thresholds.warningMm} color="var(--clay)" label="Warn" />
    {daily.map((d, i) => {
      const col = d.rain_mm >= thresholds.warningMm ? 'var(--clay)' : d.rain_mm >= thresholds.watchMm ? 'var(--gold)' : 'var(--green)';
      const x = padL + i * bw + bw * 0.2, w = bw * 0.6, h = Math.max(2, (d.rain_mm / max) * ih), today = i === 0;
      return <g key={d.date} opacity={d.complete ? 1 : .45}>
        <rect x={x} y={y(d.rain_mm)} width={w} height={h} rx="4" fill={col} />
        <text x={x + w / 2} y={y(d.rain_mm) - 5} textAnchor="middle" fontSize="10" fontWeight="700" fill="var(--ink-soft)" fontFamily="'Hanken Grotesk',sans-serif">{Math.round(d.rain_mm)}</text>
        <text x={x + w / 2} y={H - 16} textAnchor="middle" fontSize="11" fontWeight={today ? 800 : 600} fill={today ? 'var(--green-d)' : 'var(--ink-soft)'} fontFamily="'Hanken Grotesk',sans-serif">{today ? 'Now' : rDay(d.date).slice(0, 2)}</text>
        <text x={x + w / 2} y={H - 4} textAnchor="middle" fontSize="9.5" fill="var(--ink-faint)" fontFamily="'DM Mono',monospace">{rDay(d.date, { day: 'numeric' })}</text>
      </g>;
    })}
  </svg>;
}

function RainAlertCard({ a }) {
  const s = RLEVEL[a.level] || RLEVEL.info;
  return <div style={{ border: '1px solid ' + s.bd, background: s.bg, borderRadius: 18, padding: '15px 16px' }}>
    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
      <span style={{ width: 38, height: 38, borderRadius: 11, background: s.c, color: '#fff', display: 'grid', placeItems: 'center', flex: '0 0 auto' }}><Icon name={a.type === 'dry_spell' ? 'sun' : 'rain'} size={20} /></span>
      <div style={{ minWidth: 0, flex: 1 }}>
        <div className="serif" style={{ fontWeight: 800, fontSize: 16.5, lineHeight: 1.15 }}>{a.title}</div>
        <div className="mono" style={{ fontSize: 11, color: 'var(--ink-soft)', marginTop: 3 }}>{rRange(a.from, a.to)}{a.type === 'heavy_rain' && ` · ${a.rain_mm} mm/day`}</div>
      </div>
      <span style={{ fontSize: 10, fontWeight: 800, textTransform: 'uppercase', letterSpacing: '.05em', color: s.c, border: '1.5px solid ' + s.bd, padding: '3px 8px', borderRadius: 6, flex: '0 0 auto' }}>{s.t}</span>
    </div>
    <p style={{ margin: '11px 0 0', fontSize: 13.5, color: 'var(--ink)', lineHeight: 1.55 }}><strong style={{ color: s.c }}>What to do:</strong> {a.advice}</p>
  </div>;
}

function RainBanner({ prov, go, style }) {
  const a = RAIN_SAMPLE(prov).alerts[0];
  if (!a) return null;
  const s = RLEVEL[a.level] || RLEVEL.info;
  return <button onClick={() => go('rain')} style={{ width: '100%', textAlign: 'left', display: 'flex', alignItems: 'center', gap: 11, padding: '12px 14px', borderRadius: 16, border: '1px solid ' + s.bd, background: s.bg, ...style }}>
    <span style={{ width: 36, height: 36, borderRadius: 10, background: s.c, color: '#fff', display: 'grid', placeItems: 'center', flex: '0 0 auto' }}><Icon name={a.type === 'dry_spell' ? 'sun' : 'rain'} size={18} /></span>
    <span style={{ minWidth: 0, flex: 1 }}>
      <span style={{ display: 'block', fontWeight: 700, fontSize: 14, color: 'var(--ink)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{a.title} · {prov}</span>
      <span style={{ display: 'block', fontSize: 12, color: 'var(--ink-soft)', marginTop: 1 }}>{rRange(a.from, a.to)} · forecast, not an official warning</span>
    </span>
    <Icon name="chev" size={17} style={{ color: s.c, transform: 'rotate(-90deg)', flex: '0 0 auto' }} />
  </button>;
}

function RainScreen({ prov, setProv, go }) {
  const [provOpen, setProvOpen] = useState(false);
  const data = RAIN_SAMPLE(prov);
  const total = Math.round(data.daily.reduce((s, d) => s + d.rain_mm, 0));
  const worst = data.alerts.find(a => a.level === 'warning') || data.alerts[0];
  return <div className="screen-pad">
    <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 10, padding: '2px 2px 0' }}>
      <div>
        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 7, color: 'var(--green)', fontWeight: 800, fontSize: 11.5, letterSpacing: '.1em', textTransform: 'uppercase', marginBottom: 8 }}>
          <span style={{ width: 16, height: 2, background: 'var(--gold)', borderRadius: 2 }}></span>Flood / Drought Risk
        </div>
        <h1 className="serif" style={{ margin: 0, fontSize: 26, fontWeight: 800, letterSpacing: '-.02em', lineHeight: 1.05 }}>Rain outlook for {prov}</h1>
      </div>
      <button onClick={() => setProvOpen(true)} aria-label="Change province" style={{ flex: '0 0 auto', marginTop: 4, display: 'inline-flex', alignItems: 'center', gap: 6, padding: '8px 12px', borderRadius: 999, border: '1.5px solid var(--green)', background: 'rgba(46,125,79,.08)', color: 'var(--green-d)', fontWeight: 700, fontSize: 13 }}>
        <Icon name="pin" size={14} /><Icon name="chev" size={14} />
      </button>
    </div>
    <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', padding: '0 2px', margin: '12px 0 0' }}>
      <Pill tone="green"><Icon name="check" size={13} /> {data.source}</Pill>
      <Pill tone="neutral"><Icon name="calendar" size={13} /> Updated {rUpdated(data.updatedAt)}</Pill>
      {data.stale && <Pill tone="gold"><Icon name="signal" size={13} /> Saved copy</Pill>}
      <Pill tone="navy"><Icon name="rain" size={13} /> {total} mm / 9 days</Pill>
    </div>

    <div style={{ marginTop: 14, padding: '0 2px 8px', display: 'flex', alignItems: 'center', gap: 8 }}>
      <h3 className="serif" style={{ margin: 0, fontSize: 17, fontWeight: 700 }}>Alerts</h3>
      <Pill tone={worst ? RLEVEL[worst.level].tone : 'green'}>{data.alerts.length ? `${data.alerts.length} active` : 'None'}</Pill>
    </div>
    <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
      {data.alerts.length ? data.alerts.map((a, i) => <RainAlertCard key={i} a={a} />) :
        <div style={{ border: '1px dashed var(--line-d)', borderRadius: 18, padding: '22px 16px', textAlign: 'center', background: 'var(--paper)' }}>
          <span style={{ width: 44, height: 44, borderRadius: 12, margin: '0 auto 8px', background: 'rgba(46,125,79,.12)', color: 'var(--green)', display: 'grid', placeItems: 'center' }}><Icon name="check" size={22} sw={2.3} /></span>
          <div style={{ fontWeight: 700, fontSize: 14.5 }}>No heavy-rain or dry-spell alerts in the forecast.</div>
        </div>}
    </div>

    <MCard pad={0} style={{ marginTop: 14, overflow: 'hidden' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '14px 16px 6px' }}>
        <Icon name="rain" size={18} style={{ color: 'var(--navy)' }} />
        <h3 className="serif" style={{ margin: 0, fontSize: 17, fontWeight: 700 }}>Daily rainfall</h3>
        <span style={{ marginLeft: 'auto', fontSize: 11, color: 'var(--ink-faint)' }}>mm · lighter = partial day</span>
      </div>
      <div style={{ padding: '4px 4px 0' }}><RainChartM daily={data.daily} thresholds={data.thresholds} /></div>
      <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', padding: '6px 16px 14px', fontSize: 11.5, color: 'var(--ink-soft)' }}>
        {[['var(--green)', 'Normal'], ['var(--gold)', `Watch ≥${data.thresholds.watchMm}`], ['var(--clay)', `Warning ≥${data.thresholds.warningMm}`]].map(([c, t]) =>
          <span key={t} style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}><span style={{ width: 11, height: 11, borderRadius: 3, background: c }}></span>{t}</span>)}
      </div>
    </MCard>

    <div style={{ marginTop: 14, position: 'relative', overflow: 'hidden', borderRadius: 20, padding: '18px', color: '#fff', background: 'linear-gradient(150deg,var(--green-l),var(--green-d))' }}>
      <h3 className="serif" style={{ margin: 0, fontSize: 18, fontWeight: 800 }}>Get these by SMS</h3>
      <p style={{ margin: '5px 0 12px', fontSize: 13, color: '#dbe7e0', lineHeight: 1.5 }}>Rain alerts for {prov} on any phone. Starting soon — save your number now.</p>
      <MButton tone="gold" full onClick={() => go('alerts')}><Icon name="phone" size={17} /> Get these by SMS</MButton>
    </div>

    <div style={{ margin: '16px 2px 0', fontSize: 11.5, color: 'var(--ink-faint)', lineHeight: 1.5, display: 'flex', flexDirection: 'column', gap: 6 }}>
      <div><strong style={{ color: 'var(--ink-soft)' }}>Not an official warning.</strong> {data.disclaimer}</div>
      <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>Official: {data.officialSources.map((s, i) => s.url
        ? <a key={i} href={s.url} target="_blank" rel="noopener" style={{ color: 'var(--green-d)', fontWeight: 600, textDecoration: 'none' }}>{s.name} ↗</a>
        : <span key={i} style={{ color: 'var(--ink-soft)', fontWeight: 600 }}>{s.name}</span>)}</div>
      <div>{data.attribution}</div>
    </div>
    <ProvincePickerSheet open={provOpen} onClose={() => setProvOpen(false)} value={prov} onChange={setProv} />
  </div>;
}

Object.assign(window, { RainScreen, RainBanner });
