/* Field Reporter ("Aster Field") — Brand theme, mobile-framed. No reporter-identity field exists anywhere. */

const REPORT_CATEGORIES = [
  { id: 'Road condition', icon: 'route' },
  { id: 'Price change', icon: 'trending-up' },
  { id: 'Water access', icon: 'droplets' },
  { id: 'Security', icon: 'shield-alert' },
  { id: 'Crop/livestock', icon: 'wheat' },
  { id: 'Other', icon: 'more-horizontal' },
];
const REPORT_STATUS_STEPS = ['Queued', 'Submitted', 'Under review', 'Acknowledged', 'Resolved'];

function PhoneFrame({ children }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'center', padding: 'var(--space-7) 0' }}>
      <div style={{ width: 360, height: 720, borderRadius: 36, border: '10px solid var(--neutral-900)', background: 'var(--surface-page)', boxShadow: 'var(--shadow-xl)', overflow: 'hidden', position: 'relative', display: 'flex', flexDirection: 'column' }}>
        <div style={{ height: 22, background: 'var(--neutral-900)', flexShrink: 0 }} />
        <div style={{ flex: 1, minHeight: 0, display: 'flex', flexDirection: 'column' }}>{children}</div>
      </div>
    </div>
  );
}

function StatusTimeline({ status }) {
  const idx = REPORT_STATUS_STEPS.indexOf(status);
  return (
    <div style={{ display: 'flex', flexDirection: 'column' }} aria-label="Report status">
      {REPORT_STATUS_STEPS.map(function (s, i) {
        const done = i <= idx;
        const isCurrent = i === idx;
        return (
          <div key={s} style={{ display: 'flex', gap: 10 }}>
            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
              <div style={{ width: 18, height: 18, borderRadius: '50%', boxSizing: 'border-box', background: done ? 'var(--brand)' : 'var(--surface-sunken)', border: '2px solid ' + (done ? 'var(--brand)' : 'var(--border-default)'), flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                {done && Ic('check', { width: 10, height: 10, style: { color: '#fff', strokeWidth: 3.4 } })}
              </div>
              {i < REPORT_STATUS_STEPS.length - 1 && <div style={{ width: 2, flex: 1, minHeight: 16, background: i < idx ? 'var(--brand)' : 'var(--border-subtle)' }} />}
            </div>
            <div style={{ paddingBottom: i < REPORT_STATUS_STEPS.length - 1 ? 14 : 0 }}>
              <span style={{ font: (done ? '600 ' : '400 ') + '13px var(--font-text)', color: done ? 'var(--text-strong)' : 'var(--text-subtle)' }}>{s}</span>
              {isCurrent && <span style={{ display: 'block', font: '11px var(--font-text)', color: 'var(--text-subtle)', marginTop: 1 }}>Current status</span>}
            </div>
          </div>
        );
      })}
    </div>
  );
}

function FieldApp() {
  const store = useAsterStore();
  const [view, setView] = React.useState('home');
  const [offline, setOffline] = React.useState(false);
  const [selectedReportId, setSelectedReportId] = React.useState(null);
  const [selectedAlertId, setSelectedAlertId] = React.useState(null);
  const [ackAlerts, setAckAlerts] = React.useState({});
  const [toast, setToast, toastNode] = useToast();

  const alerts = store.villages
    .map(function (v) { return { village: v, syn: store.synthesis[v.id] }; })
    .filter(function (x) { return x.syn.level === 'warning' || x.syn.level === 'severe'; })
    .sort(function (a, b) { return window.AsterStore.levelRank(b.syn.level) - window.AsterStore.levelRank(a.syn.level); })
    .slice(0, 6);

  const myReports = store.fieldReports; // demo: shared feed acts as "my reports" since there's no login
  const queuedCount = myReports.filter(function (r) { return r.syncStatus === 'queued'; }).length;
  const selectedReport = myReports.find(function (r) { return r.id === selectedReportId; });
  const selectedAlert = alerts.find(function (x) { return x.village.id === selectedAlertId; });

  function goHome() { setView('home'); }
  function toggleOnline() {
    if (offline) {
      setOffline(false);
      if (queuedCount > 0) { window.AsterStore.syncQueuedReports(); setToast(queuedCount + ' queued report' + (queuedCount > 1 ? 's' : '') + ' synced.'); }
      else setToast({ message: 'Back online.', tone: 'info' });
    } else {
      setOffline(true);
      setToast({ message: 'Offline mode — reports will queue locally.', tone: 'info' });
    }
  }

  return (
    <PhoneFrame>
      <div style={{ flexShrink: 0, padding: '12px 16px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', borderBottom: '1px solid var(--border-subtle)', background: 'var(--surface-card)' }}>
        {view !== 'home' ? (
          <IconButton label="Back" variant="ghost" size="sm" onClick={goHome}>{Ic('arrow-left', { width: 16, height: 16 })}</IconButton>
        ) : (
          <div style={{ font: '700 15px var(--font-display)', color: 'var(--text-strong)' }}>Aster Field</div>
        )}
        <button className="ap-chip" onClick={toggleOnline} title="Toggle connectivity (demo)"
          style={{ display: 'flex', alignItems: 'center', gap: 6, border: '1px solid var(--border-default)', borderRadius: 'var(--radius-pill)', padding: '4px 10px', background: offline ? 'var(--severe-soft)' : 'var(--calm-soft)', cursor: 'pointer' }}>
          <span style={{ width: 7, height: 7, borderRadius: '50%', background: offline ? 'var(--severe)' : 'var(--calm)' }} />
          <span style={{ font: '11px var(--font-mono)', color: offline ? 'var(--severe-strong)' : 'var(--calm-strong)' }}>{offline ? 'OFFLINE' : 'ONLINE'}</span>
        </button>
      </div>

      <div className="ap-scroll" style={{ flex: 1, overflow: 'auto', padding: 16, paddingBottom: 90 }}>
        {offline && view === 'home' && (
          <div style={{ marginBottom: 12 }}>
            <AlertBanner level="watch" title="You're offline" icon={Ic('wifi-off', { width: 16, height: 16 })}>
              New reports will be queued and synced automatically once you're back online.{queuedCount > 0 ? ' ' + queuedCount + ' report' + (queuedCount > 1 ? 's' : '') + ' waiting to sync.' : ''}
            </AlertBanner>
          </div>
        )}

        {view === 'home' && (
          <div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
              <span style={{ font: '600 12px var(--font-text)', color: 'var(--text-muted)' }}>Nearby alerts</span>
              <span style={{ font: '11px var(--font-mono)', color: 'var(--text-subtle)' }}>{alerts.length} active</span>
            </div>
            {alerts.length === 0 && <EmptyState icon="bell-off" text="No active alerts nearby." />}
            {alerts.map(function (x) {
              const acked = !!ackAlerts[x.village.id];
              return (
                <Card key={x.village.id} interactive padding="md" elevation="sm" className="ap-hover-lift" style={{ marginBottom: 10, cursor: 'pointer' }}
                  onClick={function () { setSelectedAlertId(x.village.id); setView('alert-detail'); }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', gap: 8 }}>
                    <div style={{ font: '600 13px var(--font-text)', color: 'var(--text-strong)' }}>{x.village.name}</div>
                    <AlertLevel level={x.syn.level} size="sm" />
                  </div>
                  <div style={{ font: '12px var(--font-text)', color: 'var(--text-muted)', marginTop: 4 }}>{x.village.township}, {x.village.region} · lead time {x.syn.leadTime}</div>
                  {acked && <div style={{ marginTop: 6 }}><Badge tone="calm" dot>Acknowledged</Badge></div>}
                </Card>
              );
            })}
          </div>
        )}

        {view === 'report-form' && <ReportFormScreen offline={offline} onSubmit={function (data) {
          const r = window.AsterStore.fileFieldReport(Object.assign({}, data, { offline: offline }));
          setSelectedReportId(r.id); setView('report-detail'); setToast('Report ' + (offline ? 'queued' : 'submitted') + '.');
        }} onCancel={goHome} />}

        {view === 'report-detail' && selectedReport && (
          <div>
            <div style={{ textAlign: 'center', marginBottom: 20 }}>
              <div className="ap-pop" style={{ display: 'inline-flex', width: 52, height: 52, borderRadius: '50%', background: selectedReport.syncStatus === 'queued' ? 'var(--watch-soft)' : 'var(--calm-soft)', alignItems: 'center', justifyContent: 'center' }}>
                {Ic(selectedReport.syncStatus === 'queued' ? 'clock' : 'check', { width: 24, height: 24, style: { color: selectedReport.syncStatus === 'queued' ? 'var(--watch-strong)' : 'var(--calm-strong)', strokeWidth: 2.6 } })}
              </div>
              <div style={{ font: '600 15px var(--font-text)', color: 'var(--text-strong)', marginTop: 10 }}>
                {selectedReport.syncStatus === 'queued' ? 'Report queued — will sync when online' : 'Report submitted'}
              </div>
              <div style={{ font: '11px var(--font-mono)', color: 'var(--text-subtle)', marginTop: 4 }}>Ref {selectedReport.id.toUpperCase()}</div>
            </div>
            <Card padding="md" elevation="sm" style={{ marginBottom: 16 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', gap: 8, marginBottom: 4 }}>
                <span style={{ font: '600 13px var(--font-text)' }}>{selectedReport.category}</span>
                <Badge tone={selectedReport.severity}>{LEVEL_LABEL[selectedReport.severity] || selectedReport.severity}</Badge>
              </div>
              <div style={{ font: '13px/1.5 var(--font-text)', color: 'var(--text-body)' }}>{selectedReport.description}</div>
              <div style={{ font: '11px var(--font-mono)', color: 'var(--text-subtle)', marginTop: 6 }}>{fmtRelative(selectedReport.timestamp)}</div>
            </Card>
            <StatusTimeline status={selectedReport.syncStatus === 'queued' ? 'Queued' : 'Submitted'} />
          </div>
        )}

        {view === 'my-reports' && (
          <div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
              <span style={{ font: '600 12px var(--font-text)', color: 'var(--text-muted)' }}>My reports</span>
              {queuedCount > 0 && <Badge tone="watch">{queuedCount} queued</Badge>}
            </div>
            {myReports.length === 0 && <EmptyState icon="clipboard" text="No reports filed yet."
              action={<Button variant="secondary" size="sm" onClick={function () { setView('report-form'); }}>File your first report</Button>} />}
            {myReports.map(function (r) {
              return (
                <Card key={r.id} interactive padding="md" elevation="sm" className="ap-hover-lift" style={{ marginBottom: 10, cursor: 'pointer' }}
                  onClick={function () { setSelectedReportId(r.id); setView('report-detail'); }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', gap: 8 }}>
                    <div style={{ font: '600 13px var(--font-text)', color: 'var(--text-strong)' }}>{r.category}</div>
                    <Badge tone={r.syncStatus === 'queued' ? 'watch' : 'calm'}>{r.syncStatus === 'queued' ? 'Queued' : 'Submitted'}</Badge>
                  </div>
                  <div style={{ font: '12px var(--font-text)', color: 'var(--text-muted)', marginTop: 4 }}>{r.description.slice(0, 60)}{r.description.length > 60 ? '…' : ''}</div>
                  <div style={{ font: '10px var(--font-mono)', color: 'var(--text-subtle)', marginTop: 4 }}>{fmtRelative(r.timestamp)}</div>
                </Card>
              );
            })}
          </div>
        )}

        {view === 'alert-detail' && selectedAlert && (
          <div className="ap-rise">
            <div style={{ marginBottom: 12 }}><AlertLevel level={selectedAlert.syn.level} live /></div>
            <h2 style={{ margin: '0 0 4px', font: '700 18px var(--font-display)' }}>{selectedAlert.village.name}</h2>
            <div style={{ font: '12px var(--font-text)', color: 'var(--text-muted)', marginBottom: 12 }}>{selectedAlert.village.township}, {selectedAlert.village.region} · lead time {selectedAlert.syn.leadTime}</div>
            <div style={{ marginBottom: 12 }}>
              <Sparkline points={store.trends[selectedAlert.village.id].composite} color={LEVEL_COLOR[selectedAlert.syn.level]} width={200} height={36} />
            </div>
            <div style={{ font: '600 12px var(--font-text)', color: 'var(--text-muted)', marginBottom: 6 }}>What's driving this</div>
            <ul style={{ margin: '0 0 14px', paddingLeft: 18, font: '13px/1.6 var(--font-text)' }}>
              {selectedAlert.syn.keyDrivers.map(function (d, i) { return <li key={i}>{d}</li>; })}
            </ul>
            <div style={{ font: '600 12px var(--font-text)', color: 'var(--text-muted)', marginBottom: 6 }}>Recommended actions</div>
            <ul style={{ margin: '0 0 16px', paddingLeft: 18, font: '13px/1.6 var(--font-text)' }}>
              {selectedAlert.syn.recommendedActions.map(function (a, i) { return <li key={i}>{a}</li>; })}
            </ul>
            {ackAlerts[selectedAlert.village.id] ? (
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
                <Badge tone="calm" dot>Acknowledged</Badge>
                <Button variant="secondary" size="sm" onClick={function () { setView('report-form'); }}>File a related report</Button>
              </div>
            ) : (
              <Button variant="primary" fullWidth onClick={function () { setAckAlerts(Object.assign({}, ackAlerts, { [selectedAlert.village.id]: true })); setToast('Alert acknowledged.'); }}>Acknowledge</Button>
            )}
          </div>
        )}
      </div>

      <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, background: 'var(--surface-card)', borderTop: '1px solid var(--border-subtle)', display: 'flex', alignItems: 'center', justifyContent: 'space-around', height: 64 }}>
        <button className="ap-pressable" onClick={goHome} aria-label="Home" style={{ background: 'none', border: 'none', cursor: 'pointer', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2, color: view === 'home' ? 'var(--brand)' : 'var(--text-subtle)' }}>
          {Ic('home', { width: 18, height: 18 })}<span style={{ font: '10px var(--font-text)' }}>Home</span>
        </button>
        <button className="ap-pressable" onClick={function () { setView('report-form'); }} aria-label="New report" style={{
          width: 52, height: 52, borderRadius: '50%', background: 'var(--brand)', color: 'var(--text-on-brand)', border: 'none', cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center', boxShadow: 'var(--shadow-brand)', marginTop: -24,
        }}>{Ic('plus', { width: 22, height: 22 })}</button>
        <button className="ap-pressable" onClick={function () { setView('my-reports'); }} aria-label="My reports" style={{ background: 'none', border: 'none', cursor: 'pointer', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2, color: view === 'my-reports' ? 'var(--brand)' : 'var(--text-subtle)', position: 'relative' }}>
          {Ic('clipboard-list', { width: 18, height: 18 })}<span style={{ font: '10px var(--font-text)' }}>My reports</span>
          {queuedCount > 0 && <span style={{ position: 'absolute', top: -3, right: -6, minWidth: 15, height: 15, borderRadius: 8, background: 'var(--watch)', color: '#fff', font: '600 9px var(--font-mono)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '0 3px' }}>{queuedCount}</span>}
        </button>
      </div>
      {toastNode}
    </PhoneFrame>
  );
}

function ReportFormScreen({ offline, onSubmit, onCancel }) {
  const [category, setCategory] = React.useState(REPORT_CATEGORIES[0].id);
  const [severity, setSeverity] = React.useState('watch');
  const [description, setDescription] = React.useState('');
  const [photo, setPhoto] = React.useState(false);

  return (
    <div>
      <h2 style={{ margin: '0 0 4px', font: '700 17px var(--font-display)' }}>New report</h2>
      <div style={{ font: '12px var(--font-text)', color: 'var(--text-subtle)', marginBottom: 14 }}>Reports are anonymous by design — no reporter identity is ever attached.</div>

      <div style={{ font: '600 12px var(--font-text)', color: 'var(--text-muted)', marginBottom: 6 }}>Category</div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 6, marginBottom: 14 }}>
        {REPORT_CATEGORIES.map(function (c) {
          const selected = category === c.id;
          return (
            <button key={c.id} className="ap-chip" aria-pressed={selected} onClick={function () { setCategory(c.id); }} style={{
              display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4, padding: '10px 4px', borderRadius: 'var(--radius-card)', cursor: 'pointer', font: '11px var(--font-text)',
              border: '1px solid ' + (selected ? 'var(--brand)' : 'var(--border-default)'),
              background: selected ? 'var(--surface-brand-soft)' : 'var(--surface-card)',
              color: selected ? 'var(--brand)' : 'var(--text-body)',
            }}>
              {Ic(c.icon, { width: 16, height: 16 })}{c.id}
            </button>
          );
        })}
      </div>

      <div style={{ font: '600 12px var(--font-text)', color: 'var(--text-muted)', marginBottom: 6 }}>Severity</div>
      <div style={{ display: 'flex', gap: 6, marginBottom: 14 }}>
        {['watch', 'warning', 'severe'].map(function (s) {
          const selected = severity === s;
          return (
            <button key={s} className="ap-chip" aria-pressed={selected} onClick={function () { setSeverity(s); }} style={{
              flex: 1, padding: '8px 0', borderRadius: 'var(--radius-control)', cursor: 'pointer', font: (selected ? '600 ' : '400 ') + '12px var(--font-text)', textTransform: 'capitalize',
              border: '1px solid ' + (selected ? LEVEL_COLOR[s] : 'var(--border-default)'),
              background: selected ? 'var(--' + s + '-soft)' : 'var(--surface-card)',
              color: selected ? 'var(--' + s + '-strong)' : 'var(--text-body)',
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
            }}>
              <span style={{ width: 7, height: 7, borderRadius: '50%', background: LEVEL_COLOR[s] }} />{s}
            </button>
          );
        })}
      </div>

      <div style={{ marginBottom: 14 }}>
        <button className="ap-chip" onClick={function () { setPhoto(!photo); }} style={{
          width: '100%', padding: '14px', borderRadius: 'var(--radius-card)', border: '1px dashed ' + (photo ? 'var(--brand)' : 'var(--border-default)'), background: photo ? 'var(--surface-brand-soft)' : 'var(--surface-sunken)',
          cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, color: photo ? 'var(--brand)' : 'var(--text-muted)',
        }}>
          {Ic(photo ? 'check' : 'camera', { width: 16, height: 16 })}
          <span style={{ font: '12px var(--font-text)' }}>{photo ? 'Photo attached — tap to remove' : 'Attach a photo (optional)'}</span>
        </button>
      </div>

      <div style={{ font: '12px var(--font-text)', color: 'var(--text-muted)', marginBottom: 14, display: 'flex', alignItems: 'center', gap: 6 }}>
        {Ic('map-pin', { width: 14, height: 14 })} Using current location (auto-detected)
      </div>

      <Textarea rows={4} value={description} maxLength={400}
        onChange={function (e) { setDescription(e.target.value); }}
        placeholder="What's happening?" />

      <div style={{ marginTop: 14 }}>
        <Button variant="primary" fullWidth disabled={!description.trim()}
          iconLeft={Ic(offline ? 'clock' : 'send', { width: 15, height: 15 })}
          onClick={function () { onSubmit({ category: category, severity: severity, description: description.trim() }); }}>
          {offline ? 'Queue report (offline)' : 'Submit report'}
        </Button>
      </div>
      <div style={{ marginTop: 8 }}>
        <Button variant="ghost" fullWidth onClick={onCancel}>Cancel</Button>
      </div>
    </div>
  );
}
