// Capture sheet — quick-capture modal triggered by pull-down on Today or from FAB.

function CaptureSheet({ visible, onClose }) {
  const [mode, setMode] = React.useState(null);
  const [text, setText] = React.useState('');
  const [saving, setSaving] = React.useState(false);

  React.useEffect(() => {
    if (!visible) {
      setMode(null);
      setText('');
    }
  }, [visible]);

  if (!visible) return null;

  const modes = [
    { id: 'journal',  icon: <IconNote   size={22} color="#fff" />, label: 'Journal',    sub: 'Mood + entities · local only', color: T.indigo },
    { id: 'memory',   icon: <IconBookmark size={22} color="#fff" />, label: 'Memory',  sub: 'Save a fact for context',       color: T.purple },
    { id: 'task',     icon: <IconCheck  size={22} color="#fff" />, label: 'Task',       sub: 'With smart reminder',           color: T.green },
    { id: 'bill',     icon: <IconCamera size={22} color="#fff" />, label: 'Bill photo', sub: 'Auto-extract amount + due',     color: T.red },
    { id: 'voice',    icon: <IconMic    size={22} color="#fff" />, label: 'Voice note', sub: 'Transcribed locally',           color: T.orange },
    { id: 'remind',   icon: <IconPin    size={22} color="#fff" />, label: 'Remind me',  sub: '"…when I get home"',            color: T.blue },
  ];

  const activeMode = modes.find(m => m.id === mode);

  const handleSave = async () => {
    if (!text.trim() || saving) return;
    setSaving(true);
    try {
      if (mode === 'memory') {
        await fetch('/api/capture/memory', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ fact: text, user: LifeData.user, category: 'note' }),
        });
      } else if (mode === 'task') {
        await fetch('/api/capture/task', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ description: text, user: LifeData.user }),
        });
      }
      // journal stays local-only for now (no cloud endpoint)
    } catch (err) {
      console.error('Capture save failed:', err);
    } finally {
      setSaving(false);
      onClose();
    }
  };

  return (
    <div onClick={onClose} style={{
      position: 'absolute', inset: 0, zIndex: 200,
      background: 'rgba(0,0,0,0.42)',
      display: 'flex', alignItems: 'flex-end',
      animation: 'fadeIn 0.25s',
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        background: T.bg, width: '100%',
        borderTopLeftRadius: 28, borderTopRightRadius: 28,
        padding: '8px 0 28px',
        maxHeight: '86%', overflowY: 'auto',
        boxShadow: '0 -8px 32px rgba(0,0,0,0.16)',
        animation: 'slideUp 0.3s cubic-bezier(.2,.8,.2,1)',
      }}>
        <div style={{ width: 40, height: 5, borderRadius: 999, background: T.label4, margin: '6px auto 14px' }} />

        {mode === null && (
          <>
            <div style={{ padding: '0 20px 14px' }}>
              <div style={{ fontSize: 13, fontWeight: 600, color: T.label2, letterSpacing: 0.4, textTransform: 'uppercase' }}>Capture</div>
              <div style={{ fontSize: 28, fontWeight: 700, letterSpacing: -0.5, marginTop: 2 }}>Quick add</div>
            </div>
            <div style={{ padding: '0 16px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
              {modes.map(m => (
                <button key={m.id} onClick={() => setMode(m.id)} style={{
                  display: 'flex', alignItems: 'center', gap: 12,
                  background: T.bg2, border: 'none', cursor: 'pointer',
                  borderRadius: 16, padding: 14, textAlign: 'left',
                  boxShadow: '0 1px 2px rgba(0,0,0,0.03)',
                }}>
                  <div style={{
                    width: 38, height: 38, borderRadius: 11,
                    background: m.color,
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    flexShrink: 0,
                  }}>{m.icon}</div>
                  <div style={{ minWidth: 0 }}>
                    <div style={{ fontSize: 14, fontWeight: 600 }}>{m.label}</div>
                    <div style={{ fontSize: 11, color: T.label2, marginTop: 1, lineHeight: '14px' }}>{m.sub}</div>
                  </div>
                </button>
              ))}
            </div>
            <div style={{ padding: '18px 20px 0', fontSize: 11, color: T.label3, textAlign: 'center', lineHeight: '16px' }}>
              <IconShield size={11} color={T.label3} /> Journal, bills & voice transcribed locally · never leave the Thinkpad
            </div>
          </>
        )}

        {mode && (
          <>
            <div style={{ padding: '0 20px 12px', display: 'flex', alignItems: 'center', gap: 10 }}>
              <button onClick={() => setMode(null)} style={{
                background: 'none', border: 'none', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 2,
                color: T.blue, fontSize: 14, padding: 0,
              }}>
                <IconChevL size={16} color={T.blue} /> Back
              </button>
              <div style={{ flex: 1 }} />
              <button onClick={handleSave} disabled={saving} style={{
                background: 'none', border: 'none', cursor: 'pointer',
                color: saving ? T.label3 : T.blue, fontSize: 15, fontWeight: 600,
              }}>{saving ? 'Saving…' : 'Save'}</button>
            </div>
            <div style={{ padding: '0 20px 8px' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <div style={{
                  width: 32, height: 32, borderRadius: 9, background: activeMode.color,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>{activeMode.icon}</div>
                <div style={{ fontSize: 22, fontWeight: 700, letterSpacing: -0.4 }}>{activeMode.label}</div>
              </div>
              <div style={{ fontSize: 13, color: T.label2, marginTop: 4 }}>{activeMode.sub}</div>
            </div>

            <div style={{ padding: '14px 16px 0' }}>
              <Card style={{ padding: 14 }}>
                <textarea
                  autoFocus
                  value={text} onChange={e => setText(e.target.value)}
                  placeholder={
                    mode === 'journal' ? 'How are you feeling? What happened?' :
                    mode === 'memory'  ? 'A fact about you to remember…' :
                    mode === 'task'    ? 'What to do, optionally "by Friday"' :
                    mode === 'bill'    ? 'Take a photo of the invoice or paste amount' :
                    mode === 'voice'   ? 'Tap mic to start' :
                                          'e.g. "remind me to refill prescription when I get home"'
                  }
                  rows={5}
                  style={{
                    width: '100%', border: 'none', outline: 'none', background: 'transparent',
                    fontSize: 16, fontFamily: 'inherit', resize: 'none', minHeight: 100,
                  }}
                />
                {(mode === 'bill' || mode === 'voice') && (
                  <div style={{
                    marginTop: 6, padding: 16, border: `1.5px dashed ${T.label4}`, borderRadius: 12,
                    display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8,
                  }}>
                    {mode === 'bill' ? <IconCamera size={32} color={T.label3} /> : <IconMic size={32} color={T.label3} />}
                    <div style={{ fontSize: 13, color: T.label2 }}>{mode === 'bill' ? 'Tap to use camera' : 'Tap to record'}</div>
                  </div>
                )}
              </Card>

              {mode === 'journal' && (
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginTop: 12 }}>
                  {['🙂 OK', '😴 tired', '😤 frustrated', '🔥 energetic', '😌 calm', '😔 low'].map(m => (
                    <span key={m} style={{
                      padding: '8px 12px', borderRadius: 999, background: T.bg2, fontSize: 13, fontWeight: 500, cursor: 'pointer',
                      border: `0.5px solid ${T.sep}`,
                    }} onClick={() => setText(t => t + (t ? ' ' : '') + m)}>{m}</span>
                  ))}
                </div>
              )}
              {mode === 'memory' && (
                <div style={{ marginTop: 12 }}>
                  <div style={{ fontSize: 11, fontWeight: 600, color: T.label2, letterSpacing: 0.3, textTransform: 'uppercase', padding: '0 6px 8px' }}>Category</div>
                  <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                    {['routine', 'diet', 'work', 'partner', 'location', 'preference'].map(c => (
                      <span key={c} style={{
                        padding: '8px 12px', borderRadius: 999, background: T.bg2, fontSize: 13, fontWeight: 500, cursor: 'pointer',
                        border: `0.5px solid ${T.sep}`,
                      }}>{c}</span>
                    ))}
                  </div>
                </div>
              )}
            </div>
          </>
        )}
      </div>

      <style>{`
        @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
        @keyframes slideUp { from { transform: translateY(100%); } to { transform: translateY(0); } }
      `}</style>
    </div>
  );
}

window.CaptureSheet = CaptureSheet;
