/* Mobile · Field Command Center
 * Digital twin widget, health score, micro-climate telemetry grid,
 * AI chat ribbon at the bottom.
 */

function MobileCommand() {
  const { t, lang, alertState, live } = useGA();

  // ticking values for telemetry, modulated by alert state
  const calmTemp = 11.4, frostTemp = -0.4, droughtTemp = 24.7;
  const calmSoil = 38.2, frostSoil = 31.8, droughtSoil = 14.6;
  const baseTemp = alertState === 'frost' ? frostTemp : alertState === 'drought' ? droughtTemp : calmTemp;
  const baseSoil = alertState === 'frost' ? frostSoil : alertState === 'drought' ? droughtSoil : calmSoil;
  const tempV = useTickingValue(baseTemp, { jitter: 0.2, interval: 1300, enabled: live });
  const soilV = useTickingValue(baseSoil, { jitter: 0.4, interval: 1700, enabled: live });
  const humV = useTickingValue(alertState === 'drought' ? 32 : 72, { jitter: 1, interval: 1500, enabled: live });
  const uvV = useTickingValue(alertState === 'drought' ? 8.6 : 2.1, { jitter: 0.3, interval: 1900, enabled: live });

  const health = alertState === 'frost' ? 64 : alertState === 'drought' ? 58 : 87;
  const trend = alertState === 'calm' ? '+4' : alertState === 'frost' ? '−18' : '−24';
  const trendColor = alertState === 'calm' ? 'var(--green)' : 'var(--red)';

  return (
    <MobileShell tab="field">
      <MobileHeader
        kicker="§ K-3 / ZONE B · LOWER RIDGE"
        en="Field Command"
        ka={I18N.ka.fieldCommand}
        ru={I18N.ru.fieldCommand}
        right={
          <div style={{ textAlign: 'right' }}>
            <div className="ga-mono" style={{ fontSize: 10.5, color: 'var(--ink-3)' }}>02:14 PM · 23 MAR</div>
            <div style={{ marginTop: 4 }}>
              <Pill color={alertState === 'calm' ? 'green' : alertState === 'frost' ? 'amber' : 'red'} size="sm">
                <LiveDot color={alertState === 'calm' ? 'green' : alertState === 'frost' ? 'amber' : 'red'} size={5} />
                {alertState === 'calm' ? 'NOMINAL' : alertState === 'frost' ? 'FROST · T-90M' : 'DROUGHT · T-6H'}
              </Pill>
            </div>
          </div>
        }
      />

      <div style={{ padding: '14px 18px 20px' }}>
        {/* Digital twin / health ring */}
        <DigitalTwinWidget health={health} trend={trend} trendColor={trendColor} alertState={alertState} />

        {/* Section: Micro-climate telemetry */}
        <div className="ga-kicker" style={{ marginTop: 22, marginBottom: 10, display: 'flex',
          justifyContent: 'space-between', alignItems: 'baseline' }}>
          <span>Soil Matrix · Canopy Climate</span>
          <span style={{ color: 'var(--ink-2)' }}>4 sensors · {live ? 'live' : 'paused'}</span>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
          <TelemetryCard
            kicker="SOIL · 30cm"
            label={I18N[lang].moisture}
            value={soilV}
            unit="%vmc"
            sub="loam · 38.5 target"
            color={alertState === 'drought' ? 'red' : alertState === 'frost' ? 'amber' : 'yellow'}
            spark={[33,34,33,32,31.5,31.8,32,31.8,31.6,31.8]}
            highlight
          />
          <TelemetryCard
            kicker="CANOPY · +2.0m"
            label={I18N[lang].temperature}
            value={tempV}
            unit="°C"
            sub="±0.2 · dew −2.1"
            color={alertState === 'frost' ? 'blue' : alertState === 'drought' ? 'red' : 'ink'}
            spark={[2.4,1.8,1.0,0.6,0.2,-0.1,-0.2,-0.3,-0.4,-0.4]}
          />
          <TelemetryCard
            kicker="REL. HUMIDITY"
            label={I18N[lang].humidity}
            value={humV}
            unit="%"
            sub="abs 8.4 g/m³"
            color="ink"
            spark={[68,70,73,75,78,82,84,85,86,86]}
          />
          <TelemetryCard
            kicker="UV · INTENSITY"
            label={I18N[lang].uvRadiation}
            value={uvV}
            unit="idx"
            sub="dly avg 2.6"
            color="ink"
            spark={[1.2,1.5,1.8,2.0,2.2,2.1,2.0,1.8,1.6,1.6]}
          />
        </div>

        {/* AI Agronomist ribbon */}
        <div className="ga-kicker" style={{ marginTop: 22, marginBottom: 10 }}>AI Agronomist · Latest</div>
        <AIRibbon alertState={alertState} />

        {/* Quick actions */}
        <div className="ga-kicker" style={{ marginTop: 22, marginBottom: 10 }}>Quick Actions</div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 8 }}>
          <ActionTile icon="drip" label="Drip" sub="zone B" />
          <ActionTile icon="shield" label="Shield" sub="frost" active />
          <ActionTile icon="spray" label="Spray" sub="schedule" />
          <ActionTile icon="more" label="More" sub="all 12" />
        </div>

        {/* 24h status strip */}
        <div className="ga-kicker" style={{ marginTop: 22, marginBottom: 8 }}>24h · soil moisture · zone B</div>
        <Panel pad={14}>
          <Hour24Chart alertState={alertState} />
        </Panel>
      </div>
    </MobileShell>
  );
}

// Digital twin: angled "land" with health ring on top
function DigitalTwinWidget({ health, trend, trendColor, alertState }) {
  const ringSize = 88;
  const r = (ringSize - 8) / 2;
  const circumference = 2 * Math.PI * r;
  const offset = circumference * (1 - health / 100);
  const ringColor = alertState === 'calm' ? '#43D67A'
    : alertState === 'frost' ? '#FFA500' : '#FF453A';

  return (
    <div style={{
      position: 'relative',
      background: 'linear-gradient(135deg, #14160F 0%, #0E1014 100%)',
      border: '1px solid var(--line-2)',
      borderRadius: 14,
      padding: 18, overflow: 'hidden', height: 160,
    }}>
      <CornerTicks color="rgba(255,214,10,0.25)" />
      {/* dot grid behind */}
      <div className="ga-dot-bg" style={{ position: 'absolute', inset: 0, opacity: 0.5 }} />
      {/* sensor twin viz */}
      <div style={{ position: 'absolute', right: 0, top: 0, bottom: 0, width: '50%' }}>
        <TwinFieldViz alertState={alertState} />
      </div>
      {/* meta */}
      <div style={{ position: 'relative' }}>
        <div className="ga-kicker">FIELD HEALTH · LIVE</div>
        <div style={{ display: 'flex', alignItems: 'flex-end', gap: 18, marginTop: 14 }}>
          {/* ring */}
          <div style={{ position: 'relative', width: ringSize, height: ringSize, flexShrink: 0 }}>
            <svg width={ringSize} height={ringSize}>
              <circle cx={ringSize/2} cy={ringSize/2} r={r} stroke="rgba(255,255,255,0.07)" strokeWidth="4" fill="none"/>
              <circle cx={ringSize/2} cy={ringSize/2} r={r} stroke={ringColor} strokeWidth="4" fill="none"
                strokeLinecap="round" strokeDasharray={circumference}
                strokeDashoffset={offset}
                transform={`rotate(-90 ${ringSize/2} ${ringSize/2})`}
                style={{ transition: 'stroke-dashoffset .8s ease' }} />
            </svg>
            <div style={{ position: 'absolute', inset: 0, display: 'flex',
              alignItems: 'center', justifyContent: 'center', flexDirection: 'column' }}>
              <span className="ga-mono ga-tnum" style={{ fontSize: 26, fontWeight: 600,
                color: ringColor, lineHeight: 1, letterSpacing: '-0.02em' }}>{health}</span>
              <span className="ga-kicker" style={{ fontSize: 8 }}>/ 100</span>
            </div>
          </div>
          {/* stats column */}
          <div style={{ flex: 1, minWidth: 0 }}>
            <div className="ga-disp" style={{ fontSize: 16, fontWeight: 600 }}>
              {alertState === 'calm' ? 'All zones nominal'
                : alertState === 'frost' ? 'Bud vulnerability rising'
                : 'Moisture stress · severe'}
            </div>
            <div style={{ marginTop: 4, fontFamily: 'var(--f-mono)', fontSize: 10.5, color: 'var(--ink-3)' }}>
              4 zones · 16 nodes · last sync 4s
            </div>
            <div style={{ marginTop: 10, display: 'flex', gap: 12, alignItems: 'baseline' }}>
              <span className="ga-mono" style={{ fontSize: 12, color: trendColor, fontWeight: 600 }}>{trend}</span>
              <span className="ga-kicker" style={{ fontSize: 8.5 }}>vs · 24h</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function TwinFieldViz({ alertState }) {
  const stripes = ['#1B2218', '#1F2A1B', '#22301E', '#1F2A1B', '#1B2218'];
  return (
    <div style={{ position: 'absolute', inset: 0,
      transform: 'perspective(360px) rotateX(50deg) translateY(20px)',
      transformOrigin: 'center bottom' }}>
      {stripes.map((c, i) => (
        <div key={i} style={{
          position: 'absolute', left: '-10%', right: '-10%',
          top: `${10 + i * 16}%`, height: '10%',
          background: c,
          borderTop: '0.5px solid rgba(255,214,10,0.18)',
          borderBottom: '0.5px solid rgba(0,0,0,0.4)',
        }} />
      ))}
      {/* sensor dots */}
      {[[20, 25], [50, 35], [75, 25], [30, 55], [60, 65], [85, 55], [40, 80]].map(([x, y], i) => (
        <div key={i} style={{
          position: 'absolute', left: `${x}%`, top: `${y}%`,
          width: 5, height: 5, borderRadius: '50%',
          background: alertState === 'frost' && (i === 1 || i === 4) ? '#FFA500'
            : alertState === 'drought' && i % 2 === 0 ? '#FF453A' : '#FFD60A',
          boxShadow: '0 0 6px currentColor',
        }} />
      ))}
    </div>
  );
}

function TelemetryCard({ kicker, label, value, unit, sub, color = 'yellow', spark, highlight }) {
  const colorMap = { yellow: '#FFD60A', amber: '#FFA500', blue: '#4FC3FF', red: '#FF453A', ink: '#FAFAFA' };
  const c = colorMap[color];
  return (
    <div style={{
      position: 'relative',
      background: highlight ? 'linear-gradient(135deg, #1A1810 0%, #14140F 100%)' : 'var(--bg-2)',
      border: `1px solid ${highlight ? 'rgba(255,214,10,0.25)' : 'var(--line-2)'}`,
      borderRadius: 10, padding: 14, overflow: 'hidden',
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
        <div className="ga-kicker" style={{ fontSize: 9 }}>{kicker}</div>
        <span style={{ width: 5, height: 5, borderRadius: '50%', background: 'var(--green)' }} className="ga-pulse-dot" />
      </div>
      <div style={{ marginTop: 14, display: 'flex', alignItems: 'baseline', gap: 4 }}>
        <span className="ga-mono ga-tnum ga-tick" key={value} style={{ fontSize: 28, fontWeight: 600,
          color: c, letterSpacing: '-0.03em', lineHeight: 1 }}>{value}</span>
        <span style={{ fontFamily: 'var(--f-mono)', fontSize: 11, color: 'var(--ink-3)' }}>{unit}</span>
      </div>
      <div style={{ marginTop: 4, fontFamily: 'var(--f-mono)', fontSize: 10, color: 'var(--ink-3)' }}>
        {label} · {sub}
      </div>
      {spark && (
        <div style={{ marginTop: 8, marginLeft: -2, marginRight: -2 }}>
          <Sparkline data={spark} color={c} width={170} height={20} />
        </div>
      )}
    </div>
  );
}

function AIRibbon({ alertState }) {
  const messages = {
    calm: { tone: 'green', kicker: 'OBSERVATION · 02:14 PM', body: 'All zones nominal. Moisture buffer is healthy through Friday — no irrigation required.', action: 'Open chat' },
    frost: { tone: 'amber', kicker: 'ACTION REQUIRED · T−90 MIN', body: 'Frost risk detected at lower-ridge zone in 90 minutes. Ambient drops to −1.2°C. Activate localized drip-irrigation to shield the buds.', action: 'Run frost shield' },
    drought: { tone: 'red', kicker: 'CRITICAL · T−6 HRS', body: 'Soil moisture below 16% across zones B & D. Recommend 4.2mm pulse on B by 18:30 — yield risk drops 22%.', action: 'Queue irrigation' },
  };
  const m = messages[alertState];
  return (
    <div style={{
      position: 'relative',
      background: m.tone === 'amber' ? 'rgba(255,165,0,0.08)' : m.tone === 'red' ? 'rgba(255,69,58,0.08)' : 'var(--bg-2)',
      border: `1px solid ${m.tone === 'amber' ? 'rgba(255,165,0,0.4)' : m.tone === 'red' ? 'rgba(255,69,58,0.4)' : 'var(--line-2)'}`,
      borderRadius: 10, padding: 14, overflow: 'hidden',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
        <LiveDot color={m.tone} size={6} />
        <span className="ga-kicker" style={{
          color: m.tone === 'amber' ? 'var(--amber)' : m.tone === 'red' ? 'var(--red)' : 'var(--green)',
        }}>{m.kicker}</span>
      </div>
      <div style={{ fontSize: 13.5, lineHeight: 1.45, color: 'var(--ink)' }}>{m.body}</div>
      <div style={{ marginTop: 12, display: 'flex', gap: 8 }}>
        <GhostButton color={m.tone === 'amber' ? 'amber' : m.tone === 'red' ? 'red' : 'yellow'}
          solid size="sm" style={{ flex: 1 }}>{m.action} →</GhostButton>
        <GhostButton color="ghost" size="sm">Snooze 15m</GhostButton>
      </div>
    </div>
  );
}

function ActionTile({ icon, label, sub, active }) {
  const iconMap = {
    drip: <svg width="22" height="22" viewBox="0 0 22 22" fill="none" stroke="currentColor" strokeWidth="1.4">
      <path d="M11 3 c -3 5 -5 8 -5 11 a 5 5 0 0 0 10 0 c 0 -3 -2 -6 -5 -11z"/></svg>,
    shield: <svg width="22" height="22" viewBox="0 0 22 22" fill="none" stroke="currentColor" strokeWidth="1.4">
      <path d="M11 2L19 5v6c0 4-3.5 7-8 9-4.5-2-8-5-8-9V5z"/><path d="M7 11l3 3 5-6"/></svg>,
    spray: <svg width="22" height="22" viewBox="0 0 22 22" fill="none" stroke="currentColor" strokeWidth="1.4">
      <rect x="7" y="6" width="8" height="12" rx="1.4"/><path d="M9 6V3h4v3"/><path d="M16 7l3-3"/></svg>,
    more: <svg width="22" height="22" viewBox="0 0 22 22" fill="none" stroke="currentColor" strokeWidth="1.4">
      <circle cx="11" cy="11" r="8"/><circle cx="11" cy="7" r="0.8" fill="currentColor"/><circle cx="11" cy="11" r="0.8" fill="currentColor"/><circle cx="11" cy="15" r="0.8" fill="currentColor"/></svg>,
  };
  return (
    <button style={{
      background: active ? 'rgba(255,214,10,0.10)' : 'var(--bg-2)',
      border: `1px solid ${active ? 'rgba(255,214,10,0.4)' : 'var(--line-2)'}`,
      borderRadius: 10, padding: '14px 6px',
      color: active ? 'var(--yellow)' : 'var(--ink)',
      display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8,
    }}>
      {iconMap[icon]}
      <div style={{ fontSize: 12, fontWeight: 600, fontFamily: 'var(--f-display)' }}>{label}</div>
      <div className="ga-kicker" style={{ fontSize: 8 }}>{sub}</div>
    </button>
  );
}

function Hour24Chart({ alertState }) {
  // 24 hour soil moisture trace
  const data = alertState === 'drought'
    ? [22,21,20,19,19,18,18,17,17,16,16,16,15,15,15,15,14,14,15,15,15,16,16,16]
    : alertState === 'frost'
    ? [38,38,37,37,36,36,35,35,34,33,33,33,32,32,32,32,32,32,31.5,31.5,31.8,31.8,31.5,31.8]
    : [38,38,38,38,37,38,38,38,38,39,39,39,38,38,38,38,38,38,38,38,38,38,38,38];
  const min = Math.min(...data) - 2, max = Math.max(...data) + 2;
  const rng = max - min;
  const w = 300, h = 90;
  const points = data.map((v, i) => [(i / 23) * w, h - ((v - min) / rng) * h]);
  const d = points.map((p, i) => `${i === 0 ? 'M' : 'L'}${p[0].toFixed(1)},${p[1].toFixed(1)}`).join(' ');
  const da = `${d} L${w},${h} L0,${h} Z`;
  const ringColor = alertState === 'drought' ? '#FF453A' : alertState === 'frost' ? '#FFA500' : '#FFD60A';
  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8,
        fontFamily: 'var(--f-mono)', fontSize: 10, color: 'var(--ink-3)' }}>
        <span>0h</span><span>6h</span><span>12h</span><span>18h</span><span>now</span>
      </div>
      <svg width="100%" height={h + 18} viewBox={`0 0 ${w} ${h + 18}`}>
        {/* gridlines */}
        {[0, 0.25, 0.5, 0.75, 1].map((p, i) => (
          <line key={i} x1="0" x2={w} y1={p * h} y2={p * h} stroke="rgba(255,255,255,0.05)" strokeWidth="0.5"/>
        ))}
        {/* target band */}
        <rect x="0" y={h - ((38 - min)/rng) * h - 6} width={w} height="12"
          fill="rgba(67,214,122,0.06)" stroke="rgba(67,214,122,0.25)" strokeDasharray="2 2"/>
        <path d={da} fill={ringColor} fillOpacity="0.15"/>
        <path d={d} stroke={ringColor} strokeWidth="1.5" fill="none" strokeLinejoin="round"/>
        {/* now marker */}
        <circle cx={w} cy={points[points.length - 1][1]} r="3" fill={ringColor} stroke="var(--bg-2)" strokeWidth="1.5"/>
        <text x={w - 30} y={points[points.length - 1][1] - 8} fontFamily="var(--f-mono)" fontSize="9" fill={ringColor}>{data[data.length - 1]}%</text>
        <text x="4" y={h + 14} fontFamily="var(--f-mono)" fontSize="9" fill="var(--ink-4)">target band 36–40%</text>
      </svg>
    </div>
  );
}

Object.assign(window, { MobileCommand });
