// IVE Mobile — Submit (B1–B5), Verifier (E1–E2), You / Settings (F2–F3)
const { IVE_C: M, DOMAINS, VERIFIER_QUEUE, MODE_THEMES } = window;
const { useTh, Eye, Hair, StatusBadge, DomainTag, ScreenHeader, Pill } = window;
const { ApertureMark, Monogram, IVEWordmark, DomainIcon } = window;

// ════════════════════════════ SUBMIT ════════════════════════════
function SubmitScreen() {
  const th = useTh();
  const [tab, setTab] = React.useState('text');
  const [text, setText] = React.useState('');
  const [stage, setStage] = React.useState('compose'); // compose · review · receipt
  const [url, setUrl] = React.useState('');
  const [claims, setClaims] = React.useState([]);

  const extract = () => {
    const parts = text.split(/(?<=[.?!])\s+/).map((s) => s.trim()).filter((s) => s.length > 12);
    setClaims(parts.slice(0, 4).map((c, i) => ({ id: i, text: c, keep: true, domain: ['scientific','journalistic','historical','legal'][i % 4] })));
    setStage('review');
  };
  const reset = () => { setText(''); setUrl(''); setClaims([]); setStage('compose'); };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <ScreenHeader eyebrow="Put a claim on the record" title="Submit" />
      <div style={{ flex: 1, overflow: 'auto', WebkitOverflowScrolling: 'touch' }}>
        {stage === 'compose' && (
          <div style={{ padding: 22 }}>
            {/* mode segmented */}
            <div style={{ display: 'flex', border: `1px solid ${th.rule}`, marginBottom: 20 }}>
              {[['text','Paste text'],['url','URL'],['file','File']].map(([k, l]) => (
                <button key={k} onClick={() => setTab(k)} style={{
                  all: 'unset', cursor: 'pointer', flex: 1, textAlign: 'center', padding: '10px 0',
                  fontFamily: 'var(--ive-mono)', fontSize: 10, letterSpacing: '0.1em', textTransform: 'uppercase',
                  background: tab === k ? M.ink : 'transparent', color: tab === k ? M.paper : th.ink2,
                }}>{l}</button>
              ))}
            </div>

            {tab === 'text' && (
              <>
                <Eye>Free text · the extractor finds claims</Eye>
                <textarea value={text} onChange={(e) => setText(e.target.value)}
                  placeholder="Paste an article, a paragraph, or a single statement…"
                  style={{
                    width: '100%', boxSizing: 'border-box', marginTop: 10, minHeight: 160, resize: 'none',
                    background: th.surface, border: `1px solid ${th.rule}`, padding: 14, color: th.ink,
                    fontFamily: 'var(--ive-serif)', fontSize: 15, lineHeight: 1.5, outline: 'none',
                  }} />
                <button onClick={() => setText("The 2026 IPCC AR7 finds anthropogenic warming has accelerated faster than previously modelled. A four-day work week increases overall productivity. South Africa's screen sector contributed over R12bn to GDP in 2024.")}
                  style={{ all: 'unset', cursor: 'pointer', marginTop: 10 }}>
                  <span className="ive-mono" style={{ fontSize: 9.5, letterSpacing: '0.08em', color: M.ochreDeep, textTransform: 'uppercase' }}>↘ paste an example</span>
                </button>
                <div style={{ marginTop: 18 }}>
                  <Pill solid disabled={text.trim().length < 12} onClick={extract} style={{ width: '100%', boxSizing: 'border-box' }}>Extract claims →</Pill>
                </div>
              </>
            )}

            {tab === 'url' && (
              <>
                <Eye>URL ingestion · metadata pre-fill</Eye>
                <input value={url} onChange={(e) => setUrl(e.target.value)} placeholder="https://…"
                  style={{ width: '100%', boxSizing: 'border-box', marginTop: 10, background: th.surface, border: `1px solid ${th.rule}`, padding: 14, color: th.ink, fontFamily: 'var(--ive-mono)', fontSize: 13, outline: 'none' }} />
                {url.length > 4 && (
                  <div style={{ marginTop: 16, background: th.surface, border: `1px solid ${th.rule}`, padding: 16 }}>
                    <Eye style={{ fontSize: 9 }}>Source quality preview</Eye>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginTop: 10 }}>
                      <div className="ive-mono" style={{ fontSize: 26, color: th.ink }}>0.78</div>
                      <div className="ive-serif" style={{ fontSize: 12.5, color: th.ink2, fontWeight: 300, lineHeight: 1.4 }}>
                        Domain reputation is high. 3 prior claims from this source averaged 0.74 EB.
                      </div>
                    </div>
                  </div>
                )}
                <div style={{ marginTop: 18 }}><Pill solid disabled={url.length < 6} onClick={extract} style={{ width: '100%', boxSizing: 'border-box' }}>Ingest & extract →</Pill></div>
              </>
            )}

            {tab === 'file' && (
              <>
                <Eye>PDF or image · OCR confirmation step</Eye>
                <div style={{ marginTop: 10, border: `1px dashed ${th.rule}`, padding: '40px 20px', textAlign: 'center', background: th.surface }}>
                  <ApertureMark size={48} color={th.ink3} accent={M.ochre} />
                  <div className="ive-serif" style={{ fontSize: 14, color: th.ink2, fontWeight: 300, marginTop: 14 }}>Drop a PDF or photograph</div>
                  <div className="ive-mono" style={{ fontSize: 9.5, color: th.ink3, letterSpacing: '0.08em', textTransform: 'uppercase', marginTop: 6 }}>OCR runs before extraction</div>
                </div>
              </>
            )}
          </div>
        )}

        {stage === 'review' && (
          <div style={{ padding: 22 }}>
            <Eye>Extracted · accept, edit or drop</Eye>
            <div className="ive-serif" style={{ fontSize: 18, fontWeight: 300, color: th.ink, margin: '8px 0 18px' }}>
              {claims.filter((c) => c.keep).length} of {claims.length} claims selected
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              {claims.map((c) => (
                <div key={c.id} style={{ background: th.surface, border: `1px solid ${c.keep ? th.rule : th.ruleSoft}`, opacity: c.keep ? 1 : 0.5, padding: 14 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
                    <DomainTag domain={c.domain} />
                    <button onClick={() => setClaims((p) => p.map((x) => x.id === c.id ? { ...x, keep: !x.keep } : x))}
                      style={{ all: 'unset', cursor: 'pointer', fontFamily: 'var(--ive-mono)', fontSize: 9, letterSpacing: '0.1em', textTransform: 'uppercase', color: c.keep ? M.disputed : M.ochreDeep }}>
                      {c.keep ? '✕ drop' : '+ keep'}
                    </button>
                  </div>
                  <div className="ive-serif" style={{ fontSize: 14, color: th.ink, fontWeight: 300, lineHeight: 1.35, textWrap: 'pretty' }}>{c.text}</div>
                </div>
              ))}
            </div>
            <div style={{ display: 'flex', gap: 10, marginTop: 22 }}>
              <Pill onClick={reset} style={{ flex: 1 }}>Cancel</Pill>
              <Pill solid onClick={() => setStage('receipt')} disabled={claims.filter((c) => c.keep).length === 0} style={{ flex: 2 }}>Submit {claims.filter((c) => c.keep).length} →</Pill>
            </div>
          </div>
        )}

        {stage === 'receipt' && (
          <div style={{ padding: '40px 22px', textAlign: 'center' }}>
            <div style={{ display: 'flex', justifyContent: 'center' }}><ApertureMark size={84} color={th.ink} accent={M.ochre} /></div>
            <div className="ive-serif" style={{ fontSize: 24, fontWeight: 300, color: th.ink, marginTop: 24, letterSpacing: '-0.01em' }}>On the record.</div>
            <div className="ive-serif" style={{ fontSize: 14, color: th.ink2, fontWeight: 300, marginTop: 10, lineHeight: 1.5, maxWidth: 280, marginInline: 'auto' }}>
              {claims.filter((c) => c.keep).length} claims entered the queue. You'll be notified as each is scored.
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 1, marginTop: 28, background: th.rule, border: `1px solid ${th.rule}` }}>
              <Receipt label="Queue position" value="#34" />
              <Receipt label="Est. time to score" value="~6h" />
            </div>
            <div style={{ marginTop: 24 }}><Pill solid onClick={reset} style={{ width: '100%', boxSizing: 'border-box' }}>Submit another</Pill></div>
          </div>
        )}
      </div>
    </div>
  );
}

function Receipt({ label, value }) {
  const th = useTh();
  return (
    <div style={{ background: th.surface, padding: 18 }}>
      <Eye style={{ fontSize: 9 }}>{label}</Eye>
      <div className="ive-mono" style={{ fontSize: 24, color: th.ink, marginTop: 6 }}>{value}</div>
    </div>
  );
}

// ════════════════════════════ VERIFY ════════════════════════════
function VerifyScreen({ onOpen }) {
  const th = useTh();
  const [scoring, setScoring] = React.useState(null);
  const [eb, setEb] = React.useState(0.5);
  const [sc, setSc] = React.useState(0.5);

  if (scoring) {
    const item = VERIFIER_QUEUE.find((q) => q[0] === scoring);
    return (
      <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
        <ScreenHeader onBack={() => setScoring(null)} title="Score a claim" big={false} />
        <div style={{ flex: 1, overflow: 'auto', padding: 22 }}>
          <div style={{ marginBottom: 8 }}><DomainTag domain={item[2]} /></div>
          <div className="ive-serif" style={{ fontSize: 21, fontWeight: 300, lineHeight: 1.25, color: th.ink, letterSpacing: '-0.01em', textWrap: 'pretty' }}>{item[1]}</div>
          <div style={{ height: 24 }} />
          <Slider label="Evidence basis" value={eb} onChange={setEb} />
          <div style={{ height: 20 }} />
          <Slider label="Social consensus" value={sc} onChange={setSc} />
          <div style={{ height: 24 }} />
          <Eye>Attach evidence</Eye>
          <div style={{ marginTop: 10, border: `1px dashed ${th.rule}`, padding: '22px', textAlign: 'center', background: th.surface }}>
            <span className="ive-mono" style={{ fontSize: 10, color: th.ink3, letterSpacing: '0.08em', textTransform: 'uppercase' }}>+ link a source · 0 attached</span>
          </div>
          <div style={{ display: 'flex', gap: 10, marginTop: 24 }}>
            <Pill onClick={() => setScoring(null)} style={{ flex: 1 }}>Skip</Pill>
            <Pill solid onClick={() => setScoring(null)} style={{ flex: 2 }}>Submit score {eb.toFixed(2)} / {sc.toFixed(2)}</Pill>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <ScreenHeader eyebrow="Verifier · scientific track" title="Your queue" />
      <div style={{ flex: 1, overflow: 'auto' }}>
        {/* reputation strip */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', borderBottom: `1px solid ${th.rule}` }}>
          <Metric label="Reputation" value="0.91" />
          <Metric label="Scored" value="284" border />
          <Metric label="Upheld" value="96%" border />
        </div>
        <div style={{ padding: 18, display: 'flex', flexDirection: 'column', gap: 12 }}>
          {VERIFIER_QUEUE.map((q) => (
            <button key={q[0]} onClick={() => { setScoring(q[0]); setEb(0.5); setSc(0.5); }} style={{
              all: 'unset', cursor: 'pointer', display: 'block', background: th.surface, border: `1px solid ${th.rule}`, padding: 16,
            }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
                <DomainTag domain={q[2]} />
                <span className="ive-mono" style={{ fontSize: 8.5, letterSpacing: '0.12em', textTransform: 'uppercase', color: q[3] === 'high' ? M.ochreDeep : th.ink3 }}>{q[3]} priority</span>
              </div>
              <div className="ive-serif" style={{ fontSize: 15.5, fontWeight: 300, lineHeight: 1.3, color: th.ink, textWrap: 'pretty' }}>{q[1]}</div>
              <div className="ive-mono" style={{ fontSize: 9.5, color: M.ochreDeep, letterSpacing: '0.1em', textTransform: 'uppercase', marginTop: 12 }}>Score this →</div>
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}

function Slider({ label, value, onChange }) {
  const th = useTh();
  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 8 }}>
        <Eye>{label}</Eye>
        <span className="ive-mono" style={{ fontSize: 20, color: th.ink, fontVariantNumeric: 'tabular-nums' }}>{value.toFixed(2)}</span>
      </div>
      <input type="range" min="0" max="1" step="0.01" value={value} onChange={(e) => onChange(parseFloat(e.target.value))}
        style={{ width: '100%', accentColor: M.ochre }} />
    </div>
  );
}

function Metric({ label, value, border }) {
  const th = useTh();
  return (
    <div style={{ padding: '16px 18px', borderLeft: border ? `1px solid ${th.rule}` : 'none' }}>
      <Eye style={{ fontSize: 8.5 }}>{label}</Eye>
      <div className="ive-mono" style={{ fontSize: 22, color: th.ink, marginTop: 4 }}>{value}</div>
    </div>
  );
}

// ════════════════════════════ YOU / SETTINGS ════════════════════
function YouScreen({ mode, onSetMode, role, onSetRole }) {
  const th = useTh();
  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <ScreenHeader eyebrow="Account · preferences" title="You" />
      <div style={{ flex: 1, overflow: 'auto' }}>
        {/* identity */}
        <div style={{ padding: 22, display: 'flex', alignItems: 'center', gap: 16, borderBottom: `1px solid ${th.rule}` }}>
          <div style={{ width: 56, height: 56, background: th.dark ? th.surface : M.ink, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
            <Monogram size={40} color={M.paper} accent={M.ochre} />
          </div>
          <div>
            <div className="ive-serif" style={{ fontSize: 20, fontWeight: 300, color: th.ink }}>Reader · anon-7f2</div>
            <div className="ive-mono" style={{ fontSize: 9.5, color: th.ink3, letterSpacing: '0.08em', textTransform: 'uppercase', marginTop: 4 }}>
              {role === 'verifier' ? 'Verifier · scientific · rep 0.91' : 'Reader track · 6 domains followed'}
            </div>
          </div>
        </div>

        {/* audience mode — live theme switch */}
        <div style={{ padding: '22px 22px 8px' }}>
          <Eye>Audience mode · changes this app live</Eye>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginTop: 14 }}>
            {Object.entries(MODE_THEMES).map(([k, m]) => {
              const on = mode === k;
              return (
                <button key={k} onClick={() => onSetMode(k)} style={{
                  all: 'unset', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 14,
                  border: `1px solid ${on ? M.ochre : th.rule}`, padding: 14, background: on ? 'rgba(111,125,58,0.08)' : th.surface,
                }}>
                  <span style={{ width: 34, height: 34, flexShrink: 0, background: k === 'civic' ? '#1E2A1A' : M.paper, border: `1px solid ${th.rule}`, position: 'relative' }}>
                    <span style={{ position: 'absolute', inset: 8, background: k === 'field' ? 'transparent' : (k === 'civic' ? M.ochre : M.ink),
                      backgroundImage: k === 'field' ? `linear-gradient(${M.field} 1px, transparent 1px), linear-gradient(90deg, ${M.field} 1px, transparent 1px)` : 'none', backgroundSize: '5px 5px' }} />
                  </span>
                  <div style={{ flex: 1 }}>
                    <div className="ive-serif" style={{ fontSize: 15, color: th.ink }}>{m.name}</div>
                    <div className="ive-mono" style={{ fontSize: 9, color: th.ink3, letterSpacing: '0.06em', textTransform: 'uppercase', marginTop: 2 }}>
                      {k === 'atrium' ? 'Academic & corporate' : k === 'field' ? 'Under-16 · learners' : 'General public'}
                    </div>
                  </div>
                  <span style={{ width: 10, height: 10, border: `1px solid ${on ? M.ochre : th.ink3}`, background: on ? M.ochre : 'transparent', borderRadius: '50%' }} />
                </button>
              );
            })}
          </div>
        </div>

        {/* settings list */}
        <div style={{ padding: '14px 22px 30px' }}>
          <SetRow label="Track" detail={role === 'verifier' ? 'Verifier' : 'Reader'} onClick={() => onSetRole(role === 'verifier' ? 'reader' : 'verifier')} />
          <SetRow label="Notifications" detail="Recheck · disputes" />
          <SetRow label="Accessibility" detail="Type · contrast · motion" />
          <SetRow label="Family / institutional" detail="Field Notes default" />
          <SetRow label="API & integrations" detail="Developer" last />
        </div>
      </div>
    </div>
  );
}

function SetRow({ label, detail, onClick, last }) {
  const th = useTh();
  return (
    <button onClick={onClick} style={{ all: 'unset', cursor: onClick ? 'pointer' : 'default', display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '14px 0', borderBottom: last ? 'none' : `0.5px solid ${th.ruleSoft}`, width: '100%' }}>
      <span className="ive-serif" style={{ fontSize: 15, color: th.ink, fontWeight: 300 }}>{label}</span>
      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
        <span className="ive-mono" style={{ fontSize: 10, color: th.ink3, letterSpacing: '0.06em', textTransform: 'uppercase' }}>{detail}</span>
        <svg width="6" height="11" viewBox="0 0 6 11"><path d="M1 1l4 4.5L1 10" stroke={th.ink3} strokeWidth="1.3" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
      </span>
    </button>
  );
}

Object.assign(window, { SubmitScreen, VerifyScreen, YouScreen });
