/* Mobile · Frost Alert detail / acknowledge flow */

function MobileAlert() {
  const { lang, alertState } = useGA();
  const [stage, setStage] = React.useState('detail'); // 'detail' | 'confirming' | 'queued'

  const states = {
    frost:   { tone: 'amber', label: 'FROST RISK · T−90 MIN', temp: '−1.2°C', delta: '−3.4°C in 90m', vol: '4.2 mm', dur: '40 min', cost: '₾28', risk: '↓ 22%' },
    drought: { tone: 'red',   label: 'DROUGHT STRESS · T−6 HRS', temp: '14.6 %vmc', delta: '−6.0 % in 24h', vol: '8.6 mm', dur: '90 min', cost: '₾62', risk: '↓ 31%' },
    calm:    { tone: 'green', label: 'NOMINAL · NO ACTION', temp: '—', delta: '—', vol: '—', dur: '—', cost: '—', risk: '—' },
  };
  const s = states[alertState];
  const tone = s.tone;
  const toneColor = tone === 'amber' ? '#FFA500' : tone === 'red' ? '#FF453A' : '#43D67A';

  return (
    <MobileShell tab="alerts">
      {/* Custom header — no sticky chrome */}
      <div style={{ padding: '14px 18px 8px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 14 }}>
          <button style={{ width: 30, height: 30, borderRadius: 8,
            background: 'var(--bg-2)', border: '1px solid var(--line-2)',
            color: 'var(--ink)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <svg width="12" height="12" viewBox="0 0 12 12"><path d="M8 1L3 6l5 5" stroke="currentColor" strokeWidth="1.5" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
          </button>
          <span className="ga-kicker">ALERT #K3-B-014 · 23 MAR 14:14</span>
          <div style={{ marginLeft: 'auto', display: 'flex', gap: 8 }}>
            <Pill color="ghost" size="sm">SHARE</Pill>
            <Pill color="ghost" size="sm">···</Pill>
          </div>
        </div>

        {/* Pulsing alert head */}
        <div style={{
          position: 'relative', overflow: 'hidden',
          background: tone === 'amber' ? 'linear-gradient(180deg, rgba(255,165,0,0.14), rgba(255,165,0,0.04))'
                    : tone === 'red'   ? 'linear-gradient(180deg, rgba(255,69,58,0.14), rgba(255,69,58,0.04))'
                    : 'var(--bg-2)',
          border: `1px solid ${toneColor}66`,
          borderRadius: 14, padding: '20px 18px 22px',
        }}>
          <CornerTicks color={`${toneColor}55`} />

          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <LiveDot color={tone} size={9} />
            <span className="ga-kicker" style={{ color: toneColor, fontSize: 10.5 }}>{s.label}</span>
          </div>

          <h1 className="ga-disp" style={{ fontSize: 30, fontWeight: 600, lineHeight: 1.05,
            letterSpacing: '-0.02em', margin: '14px 0 4px' }}>
            {alertState === 'frost' ? 'Activate drip-irrigation to shield buds.'
            : alertState === 'drought' ? 'Pulse zones B & D to keep yield.'
            : 'All systems nominal.'}
          </h1>
          {lang !== 'en' && (
            <div style={{ fontSize: 13, color: 'var(--ink-3)', marginTop: 4 }}>
              {lang === 'ka'
                ? 'წვეთოვანი მორწყვა — კვირტების დასაცავად.'
                : 'Капельный полив — для защиты почек.'}
            </div>
          )}

          {alertState !== 'calm' && (
            <div style={{ marginTop: 14, display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 0,
              borderTop: `1px dashed ${toneColor}44`, paddingTop: 12 }}>
              <AlertStat k="PREDICTED" v={s.temp} color={toneColor} />
              <AlertStat k="DELTA" v={s.delta} color={toneColor} />
              <AlertStat k="WINDOW" v="40 MIN" color={toneColor} />
            </div>
          )}
        </div>
      </div>

      <div style={{ padding: '0 18px 16px' }}>
        {/* The why */}
        <SectionLabel>The why</SectionLabel>
        <Panel pad={16}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            <ReasoningRow
              k="01 · TELEMETRY"
              t={alertState === 'drought'
                ? '5 sensors across B & D show < 18% vmc · 24h gradient −6%'
                : 'Canopy node K3-B-015 reports 0.6°C with dew point at −2.1°C'}
            />
            <ReasoningRow
              k="02 · SATELLITE"
              t="Sentinel-2 NDVI delta on lower-ridge: −0.04 in 4 days"
            />
            <ReasoningRow
              k="03 · MODEL"
              t={alertState === 'drought'
                ? 'Drought-stress regression · 91.3% confidence'
                : 'Frost-radiative model · 92.4% confidence · 89min horizon'}
            />
          </div>
        </Panel>

        {/* Recommendation */}
        <SectionLabel style={{ marginTop: 18 }}>Recommended action</SectionLabel>
        <Panel pad={16}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
            <div>
              <Pill color={tone === 'amber' ? 'amber' : tone === 'red' ? 'red' : 'green'} size="sm">DRIP·B-01..B-05</Pill>
              <div className="ga-disp" style={{ marginTop: 8, fontSize: 16, fontWeight: 600 }}>
                Localized pulse · zone B
              </div>
              <div style={{ marginTop: 4, fontSize: 12, color: 'var(--ink-3)' }}>
                {alertState === 'drought' ? '5 valves · ramped' : '5 valves · timed for canopy warm-up'}
              </div>
            </div>
            <div style={{ textAlign: 'right' }}>
              <div className="ga-mono" style={{ fontSize: 20, fontWeight: 600, color: toneColor }}>{s.vol}</div>
              <div className="ga-kicker" style={{ fontSize: 8.5 }}>volume</div>
            </div>
          </div>
          <div style={{ marginTop: 14, paddingTop: 12, borderTop: '1px solid var(--line)',
            display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 0 }}>
            <AlertStat k="DURATION" v={s.dur} />
            <AlertStat k="COST EST" v={s.cost} />
            <AlertStat k="YIELD RISK" v={s.risk} color="var(--green)" />
          </div>
        </Panel>

        {/* Audit trail */}
        <SectionLabel style={{ marginTop: 18 }}>Audit trail · last 24h</SectionLabel>
        <Panel pad={0}>
          {[
            { t: '14:14', e: 'AI inference', d: 'frost confidence > 90%', c: toneColor },
            { t: '14:12', e: 'Sensor sync', d: '16/16 nodes · ok', c: 'var(--green)' },
            { t: '11:02', e: 'Fertilizer · A', d: '12 kg · signed', c: 'var(--ink-3)' },
            { t: '04:18', e: 'Irrigate · B-01', d: 'auto · 3.2 mm', c: 'var(--ink-3)' },
          ].map((r, i, arr) => (
            <div key={i} style={{ padding: '12px 16px',
              display: 'flex', alignItems: 'center', gap: 12,
              borderBottom: i < arr.length - 1 ? '0.5px solid var(--line)' : 'none' }}>
              <span className="ga-mono ga-tnum" style={{ width: 40, fontSize: 11, color: 'var(--ink-3)' }}>{r.t}</span>
              <span style={{ width: 6, height: 6, borderRadius: '50%', background: r.c }} />
              <span style={{ fontSize: 13, fontWeight: 500 }}>{r.e}</span>
              <span style={{ marginLeft: 'auto', fontFamily: 'var(--f-mono)', fontSize: 11, color: 'var(--ink-3)' }}>{r.d}</span>
            </div>
          ))}
        </Panel>
      </div>

      {/* Fixed bottom CTA */}
      <div style={{ height: 130 }} />
      <div style={{
        position: 'absolute', left: 0, right: 0, bottom: 92,
        padding: '14px 18px 16px',
        background: 'linear-gradient(180deg, transparent, rgba(10,10,11,0.92) 30%)',
        zIndex: 30,
      }}>
        {stage === 'queued' ? (
          <div style={{ display: 'flex', alignItems: 'center', gap: 12,
            background: 'rgba(67,214,122,0.10)', border: '1px solid rgba(67,214,122,0.4)',
            borderRadius: 12, padding: '14px 16px' }}>
            <svg width="22" height="22" viewBox="0 0 22 22" fill="none">
              <circle cx="11" cy="11" r="10" stroke="var(--green)" strokeWidth="1.4"/>
              <path d="M6 11.5l3 3 6.5-7" stroke="var(--green)" strokeWidth="1.6" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
            <div>
              <div style={{ fontWeight: 600, color: 'var(--green)' }}>Action queued</div>
              <div className="ga-mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>signed · contract #0xA1·9C32A1</div>
            </div>
          </div>
        ) : (
          <div style={{ display: 'flex', gap: 10 }}>
            <GhostButton color="ghost" size="lg" style={{ width: 110 }}>Snooze</GhostButton>
            <GhostButton color={tone === 'amber' ? 'amber' : tone === 'red' ? 'red' : 'green'}
              solid size="lg" style={{ flex: 1 }}
              onClick={() => setStage('queued')}>
              {alertState === 'calm' ? 'All clear' : 'Execute now →'}
            </GhostButton>
          </div>
        )}
      </div>
    </MobileShell>
  );
}

function AlertStat({ k, v, color }) {
  return (
    <div>
      <div className="ga-kicker" style={{ fontSize: 8.5 }}>{k}</div>
      <div className="ga-mono" style={{ fontSize: 15, fontWeight: 600,
        color: color || 'var(--ink)', marginTop: 4 }}>{v}</div>
    </div>
  );
}

function SectionLabel({ children, style = {} }) {
  return (
    <div className="ga-kicker" style={{ margin: '14px 4px 8px', ...style }}>{children}</div>
  );
}

function ReasoningRow({ k, t }) {
  return (
    <div>
      <div className="ga-kicker" style={{ color: 'var(--yellow)' }}>{k}</div>
      <div style={{ fontSize: 13, lineHeight: 1.5, color: 'var(--ink-2)', marginTop: 4 }}>{t}</div>
    </div>
  );
}

Object.assign(window, { MobileAlert });
