// screen-add.jsx — 3 capture methods: paste, photo→AI, manual.
// Includes the review screen for parsed/AI fields.

function AddCaptureScreen({ theme, dark, onClose, onSave }) {
  const [mode, setMode] = React.useState('menu'); // 'menu' | 'paste' | 'photo' | 'manual' | 'review'
  const [draft, setDraft] = React.useState(null);

  if (mode === 'review') {
    return <ReviewScreen theme={theme} dark={dark} draft={draft}
      onBack={() => setMode('menu')}
      onCancel={onClose}
      onSave={() => { onSave(draft); onClose(); }} />;
  }
  if (mode === 'paste') {
    return <PasteScreen theme={theme} dark={dark} onBack={() => setMode('menu')}
      onParsed={(d) => { setDraft(d); setMode('review'); }} />;
  }
  if (mode === 'photo') {
    return <PhotoScreen theme={theme} dark={dark} onBack={() => setMode('menu')}
      onParsed={(d) => { setDraft(d); setMode('review'); }} />;
  }
  if (mode === 'manual') {
    return <ManualScreen theme={theme} dark={dark} onBack={() => setMode('menu')}
      onParsed={(d) => { setDraft(d); setMode('review'); }} />;
  }
  return <MenuScreen theme={theme} onClose={onClose} setMode={setMode} />;
}

// ─── menu ──────────────────────────────────────────────────
function MenuScreen({ theme, onClose, setMode }) {
  const opts = [
    {
      key: 'paste', icon: 'clipboard', title: 'Paste a lead',
      sub: 'From your inbox or carsales — auto-parsed',
      tone: 'blue',
    },
    {
      key: 'photo', icon: 'camera', title: 'Photo of your book',
      sub: 'Handwritten page → AI fills the fields',
      tone: 'neutral', accent: true,
    },
    {
      key: 'manual', icon: 'edit', title: 'Quick manual entry',
      sub: 'Just typed in, walk-in style',
      tone: 'neutral',
    },
  ];
  return (
    <React.Fragment>
      <TopBar theme={theme}
        trailing={
          <button onClick={onClose} style={{
            border: 'none', background: theme.surface, width: 36, height: 36,
            borderRadius: 99, color: theme.text, cursor: 'pointer',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            border: `0.5px solid ${theme.border}`,
          }}>
            <Icon name="x" size={18}/>
          </button>
        }
      />
      <ScrollBody>
        <div style={{ padding: '4px 4px 18px' }}>
          <div style={{ fontSize: 13, fontWeight: 500, color: theme.textMute, letterSpacing: -0.1 }}>
            Capture a customer
          </div>
          <div style={{ fontSize: 30, fontWeight: 700, color: theme.text, letterSpacing: -0.6, marginTop: 2, lineHeight: '34px' }}>
            How did this one come in?
          </div>
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          {opts.map(o => (
            <button key={o.key} onClick={() => setMode(o.key)} style={{
              border: 'none', background: theme.surface,
              borderRadius: 22, padding: 18, textAlign: 'left',
              border: `0.5px solid ${theme.border}`,
              boxShadow: '0 1px 2px rgba(0,0,0,0.025)',
              display: 'flex', gap: 14, alignItems: 'center', cursor: 'pointer',
              fontFamily: 'inherit',
            }}>
              <div style={{
                width: 52, height: 52, borderRadius: 16,
                background: o.tone === 'blue' ? theme.blueSoft : theme.chip,
                color: o.tone === 'blue' ? theme.blueInk : theme.chipInk,
                display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
                position: 'relative',
              }}>
                <Icon name={o.icon} size={24} stroke={1.8}/>
                {o.accent && <span style={{
                  position: 'absolute', top: -4, right: -4,
                  width: 18, height: 18, borderRadius: 99,
                  background: theme.text, color: theme.bg,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>
                  <Icon name="sparkle" size={11} stroke={2.2}/>
                </span>}
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 17, fontWeight: 600, color: theme.text, letterSpacing: -0.2 }}>
                  {o.title}
                </div>
                <div style={{ fontSize: 13, color: theme.textMute, marginTop: 2, letterSpacing: -0.1 }}>
                  {o.sub}
                </div>
              </div>
              <Icon name="chevron" size={18} stroke={2} style={{ color: theme.textDim }}/>
            </button>
          ))}
        </div>

        <div style={{
          marginTop: 22, padding: '14px 16px', borderRadius: 16,
          background: theme.chip, color: theme.textMute,
          fontSize: 13, letterSpacing: -0.1, lineHeight: 1.45,
        }}>
          <strong style={{ color: theme.text, fontWeight: 600 }}>No phone number stored.</strong> Tap any
          customer name to ring them straight from your Contacts app.
        </div>

        <div style={{ height: 100 }} />
      </ScrollBody>
    </React.Fragment>
  );
}

// ─── paste ────────────────────────────────────────────────
function PasteScreen({ theme, dark, onBack, onParsed }) {
  const [text, setText] = React.useState('');
  const [busy, setBusy] = React.useState(false);

  const parse = () => {
    setBusy(true);
    // mock — pretend we ran a parser
    setTimeout(() => {
      const parsed = parseLeadBlock(text);
      setBusy(false);
      onParsed(parsed);
    }, 700);
  };

  return (
    <React.Fragment>
      <TopBar theme={theme} onBack={onBack} title="Paste a lead" />
      <ScrollBody>
        <div style={{ padding: '4px 4px 10px' }}>
          <div style={{ fontSize: 13, color: theme.textMute, letterSpacing: -0.1 }}>
            Paste from email, carsales, or wherever the lead came in.
          </div>
        </div>
        <div style={{
          background: theme.surface, borderRadius: 18, padding: 14,
          border: `0.5px solid ${theme.border}`,
        }}>
          <textarea value={text} onChange={e => setText(e.target.value)}
            placeholder="Paste lead text here…"
            style={{
              width: '100%', minHeight: 200, border: 'none', resize: 'none',
              fontFamily: 'inherit', fontSize: 14, color: theme.text,
              background: 'transparent', outline: 'none', lineHeight: 1.45,
              letterSpacing: -0.1,
            }}
          />
        </div>
        <button onClick={parse} disabled={!text || busy} style={{
          marginTop: 16, width: '100%', border: 'none',
          padding: '15px 20px', borderRadius: 14,
          background: text && !busy ? theme.text : theme.chip,
          color: text && !busy ? theme.bg : theme.textDim,
          fontFamily: 'inherit', fontSize: 15, fontWeight: 600,
          cursor: text && !busy ? 'pointer' : 'default',
          letterSpacing: -0.15,
        }}>{busy ? 'Parsing…' : 'Parse fields →'}</button>

        <div style={{ height: 80 }} />
      </ScrollBody>
    </React.Fragment>
  );
}

// dumb but realistic regex parser for the demo
function parseLeadBlock(text) {
  const grab = (label) => {
    const m = new RegExp('(?:' + label + ')\\s*[:\\-]\\s*(.+)', 'i').exec(text);
    return m && m[1] ? m[1].trim() : '';
  };
  return {
    name: grab('Name'),
    car: grab('Interest|Car|Vehicle'),
    location: (grab('Suburb|Location') || '').split(',')[0],
    finance: grab('Finance') || 'Unknown',
    journey: 'Just looking',
    stage: 'New lead',
    status: 'red',
    source: 'Paste · carsales.com.au',
    notes: grab('Message') || grab('Notes') || '',
    nurturing: false,
    _confidence: { name: 0.96, car: 0.88, location: 0.93, finance: 0.78, notes: 0.71 },
  };
}

// ─── photo (AI scan) ───────────────────────────────────────
// Downscale a captured photo to keep uploads small + cheap for the vision model.
function resizeToBase64(file, maxDim, quality) {
  return new Promise((resolve, reject) => {
    const img = new Image();
    const url = URL.createObjectURL(file);
    img.onload = () => {
      URL.revokeObjectURL(url);
      let w = img.width, h = img.height;
      if (w >= h && w > maxDim) { h = Math.round(h * maxDim / w); w = maxDim; }
      else if (h > maxDim) { w = Math.round(w * maxDim / h); h = maxDim; }
      const cv = document.createElement('canvas');
      cv.width = w; cv.height = h;
      cv.getContext('2d').drawImage(img, 0, 0, w, h);
      const dataUrl = cv.toDataURL('image/jpeg', quality);
      resolve({ dataUrl, base64: dataUrl.split(',')[1] });
    };
    img.onerror = reject;
    img.src = url;
  });
}

function PhotoScreen({ theme, dark, onBack, onParsed }) {
  const [phase, setPhase] = React.useState('frame'); // frame → scanning
  const [imgUrl, setImgUrl] = React.useState(null);
  const [error, setError] = React.useState('');
  const inputRef = React.useRef(null);
  const aiReady = !!(window.AI && window.AI.configured());

  const onFile = async (e) => {
    const file = e.target.files && e.target.files[0];
    e.target.value = '';
    if (!file) return;
    setError('');
    try {
      const { dataUrl, base64 } = await resizeToBase64(file, 1600, 0.85);
      setImgUrl(dataUrl);
      setPhase('scanning');
      const f = await window.AI.fromPhoto(base64, 'image/jpeg');
      onParsed({
        stage: 'New lead', status: 'neutral', source: 'Photo · book',
        name: f.name || '', car: f.car || '', location: f.location || '',
        finance: f.finance || 'Unknown', journey: f.journey || 'Just looking',
        notes: f.notes || '', nurturing: !!f.nurturing, readyDate: f.readyDate || null,
        _confidence: f._confidence || {}, _scanned: true,
      });
    } catch (err) {
      console.error(err);
      setError('Could not read that photo. Try again, or use Quick add.');
      setPhase('frame');
    }
  };

  return (
    <React.Fragment>
      <TopBar theme={theme} onBack={onBack} title="Photo to fields" />
      <ScrollBody>
        <div style={{ padding: '4px 4px 14px' }}>
          <div style={{ fontSize: 13, color: theme.textMute, letterSpacing: -0.1 }}>
            Snap a page from your carbon book. AI fills the fields — you review before saving.
          </div>
        </div>

        <input ref={inputRef} type="file" accept="image/*" capture="environment"
          onChange={onFile} style={{ display: 'none' }} />

        {/* Camera viewfinder */}
        <div style={{
          aspectRatio: '3 / 4', width: '100%', borderRadius: 20, overflow: 'hidden',
          background: dark ? '#0A0B0E' : '#E8E5DE',
          position: 'relative',
          border: `0.5px solid ${theme.border}`,
        }}>
          {imgUrl
            ? <img src={imgUrl} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
            : <PaperPreview phase={phase} theme={theme} dark={dark}/>}
          {/* scan overlay */}
          {phase === 'scanning' && (
            <div style={{
              position: 'absolute', inset: 0, pointerEvents: 'none',
              background: `linear-gradient(180deg, transparent 0%, ${theme.blue}22 50%, transparent 100%)`,
              backgroundSize: '100% 60px', backgroundRepeat: 'no-repeat',
              backgroundPosition: '0 0',
              animation: 'scanline 1.6s ease-in-out infinite',
            }} />
          )}
          {/* corner brackets */}
          {['tl', 'tr', 'bl', 'br'].map(corner => (
            <div key={corner} style={{
              position: 'absolute',
              top: corner.startsWith('t') ? 14 : 'auto',
              bottom: corner.startsWith('b') ? 14 : 'auto',
              left: corner.endsWith('l') ? 14 : 'auto',
              right: corner.endsWith('r') ? 14 : 'auto',
              width: 24, height: 24,
              borderTop: corner.startsWith('t') ? `2px solid ${theme.blue}` : 'none',
              borderBottom: corner.startsWith('b') ? `2px solid ${theme.blue}` : 'none',
              borderLeft: corner.endsWith('l') ? `2px solid ${theme.blue}` : 'none',
              borderRight: corner.endsWith('r') ? `2px solid ${theme.blue}` : 'none',
              borderTopLeftRadius: corner === 'tl' ? 8 : 0,
              borderTopRightRadius: corner === 'tr' ? 8 : 0,
              borderBottomLeftRadius: corner === 'bl' ? 8 : 0,
              borderBottomRightRadius: corner === 'br' ? 8 : 0,
            }} />
          ))}
        </div>

        {/* status line */}
        <div style={{
          textAlign: 'center', padding: '14px 0 6px',
          fontSize: 14, color: theme.textMute, letterSpacing: -0.1,
        }}>
          {phase === 'frame' && (aiReady ? 'Tap to photograph the page' : 'Photo AI not connected yet')}
          {phase === 'scanning' && (
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
              <Icon name="sparkle" size={14} style={{ color: theme.blue }}/>
              Reading handwriting…
            </span>
          )}
        </div>
        {error && <div style={{ color: theme.red, fontSize: 13, textAlign: 'center', padding: '0 0 8px' }}>{error}</div>}

        <button onClick={() => inputRef.current && inputRef.current.click()}
          disabled={phase === 'scanning' || !aiReady} style={{
          marginTop: 12, width: '100%', border: 'none',
          padding: '15px 20px', borderRadius: 14,
          background: (phase === 'frame' && aiReady) ? theme.text : theme.chip,
          color: (phase === 'frame' && aiReady) ? theme.bg : theme.textDim,
          fontFamily: 'inherit', fontSize: 15, fontWeight: 600,
          cursor: (phase === 'frame' && aiReady) ? 'pointer' : 'default',
          letterSpacing: -0.15,
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
        }}>
          <Icon name="camera" size={18} stroke={2}/>
          {phase === 'scanning' ? 'Reading…' : 'Capture page'}
        </button>

        <div style={{ height: 80 }} />
      </ScrollBody>

      <style>{`@keyframes scanline { 0% { background-position: 0 0% } 100% { background-position: 0 100% } }`}</style>
    </React.Fragment>
  );
}

function PaperPreview({ phase, theme, dark }) {
  // neutral viewfinder placeholder (no fake customer data)
  return (
    <div style={{
      position: 'absolute', inset: 0,
      display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
      gap: 12, color: dark ? 'rgba(255,255,255,0.45)' : 'rgba(0,0,0,0.40)',
    }}>
      <Icon name="camera" size={42} stroke={1.4} />
      <div style={{ fontSize: 13.5, letterSpacing: -0.1 }}>Point at your book page</div>
    </div>
  );
}

// ─── manual ────────────────────────────────────────────────
function ManualScreen({ theme, dark, onBack, onParsed }) {
  const [d, setD] = React.useState({
    name: '', car: '', location: '', finance: 'Unknown',
    journey: 'Just looking', stage: 'New lead', status: 'neutral',
    source: 'Walk-in · 24 May', notes: '', nurturing: false,
  });
  const set = (k, v) => setD(x => ({ ...x, [k]: v }));

  return (
    <React.Fragment>
      <TopBar theme={theme} onBack={onBack} title="Quick add" />
      <ScrollBody>
        <div style={{ padding: '4px 4px 10px' }}>
          <div style={{ fontSize: 13, color: theme.textMute, letterSpacing: -0.1 }}>
            Walk-in. Just the basics — fill the rest later.
          </div>
        </div>
        <div style={{
          background: theme.surface, borderRadius: 18, padding: '4px 14px',
          border: `0.5px solid ${theme.border}`,
        }}>
          <Input theme={theme} label="Name" value={d.name} onChange={v => set('name', v)} placeholder="Walk-in name"/>
          <Input theme={theme} label="Car" value={d.car} onChange={v => set('car', v)} placeholder="e.g. Compact SUV · slate"/>
          <Input theme={theme} label="Location" value={d.location} onChange={v => set('location', v)} placeholder="Suburb"/>
          <Input theme={theme} label="Notes" value={d.notes} onChange={v => set('notes', v)} placeholder="What they want, when they're back…" multi last/>
        </div>

        <div style={{ marginTop: 14, display: 'flex', flexDirection: 'column', gap: 8 }}>
          <Toggle theme={theme} label="Nurturing customer (set a ready-date)" value={d.nurturing}
            onChange={v => set('nurturing', v)} />
        </div>

        <button onClick={() => onParsed(d)} disabled={!d.name} style={{
          marginTop: 20, width: '100%', border: 'none',
          padding: '15px 20px', borderRadius: 14,
          background: d.name ? theme.text : theme.chip,
          color: d.name ? theme.bg : theme.textDim,
          fontFamily: 'inherit', fontSize: 15, fontWeight: 600,
          cursor: d.name ? 'pointer' : 'default',
          letterSpacing: -0.15,
        }}>Review and save →</button>

        <div style={{ height: 80 }} />
      </ScrollBody>
    </React.Fragment>
  );
}

function Input({ theme, label, value, onChange, placeholder, multi, last }) {
  return (
    <div style={{
      padding: '10px 0',
      borderBottom: last ? 'none' : `0.5px solid ${theme.border}`,
    }}>
      <div style={{ fontSize: 11, fontWeight: 600, color: theme.textMute, letterSpacing: 0.4, textTransform: 'uppercase' }}>{label}</div>
      {multi ? (
        <textarea value={value} onChange={e => onChange(e.target.value)} placeholder={placeholder}
          rows={3}
          style={{
            width: '100%', border: 'none', resize: 'none', background: 'transparent',
            fontFamily: 'inherit', fontSize: 16, color: theme.text, outline: 'none',
            padding: '4px 0 0', letterSpacing: -0.2, lineHeight: 1.4,
          }}
        />
      ) : (
        <input value={value} onChange={e => onChange(e.target.value)} placeholder={placeholder}
          style={{
            width: '100%', border: 'none', background: 'transparent',
            fontFamily: 'inherit', fontSize: 16, color: theme.text, outline: 'none',
            padding: '4px 0 0', letterSpacing: -0.2,
          }}
        />
      )}
    </div>
  );
}

function Toggle({ theme, label, value, onChange }) {
  return (
    <button onClick={() => onChange(!value)} style={{
      border: 'none', background: theme.surface,
      borderRadius: 14, padding: '12px 14px',
      border: `0.5px solid ${theme.border}`,
      display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12,
      fontFamily: 'inherit', cursor: 'pointer',
    }}>
      <span style={{ fontSize: 14.5, color: theme.text, letterSpacing: -0.15, textAlign: 'left' }}>{label}</span>
      <span style={{
        width: 44, height: 26, borderRadius: 99, padding: 2,
        background: value ? theme.green : theme.chip,
        transition: 'background 0.15s', flexShrink: 0,
      }}>
        <span style={{
          display: 'block', width: 22, height: 22, borderRadius: 99,
          background: '#fff', transform: value ? 'translateX(18px)' : 'translateX(0)',
          transition: 'transform 0.15s', boxShadow: '0 1px 3px rgba(0,0,0,0.18)',
        }}/>
      </span>
    </button>
  );
}

// ─── review (AI confidence) ─────────────────────────────────
function ReviewScreen({ theme, dark, draft, onBack, onCancel, onSave }) {
  const [d, setD] = React.useState(draft);
  const set = (k, v) => setD(x => ({ ...x, [k]: v }));
  const lowConf = (k) => d._confidence && d._confidence[k] !== undefined && d._confidence[k] < 0.85;

  return (
    <React.Fragment>
      <TopBar theme={theme} onBack={onBack} title="Review and save"
        trailing={
          <button onClick={onCancel} style={{
            border: 'none', background: 'transparent', color: theme.textMute,
            fontSize: 15, fontWeight: 500, fontFamily: 'inherit', cursor: 'pointer',
            padding: '6px 10px',
          }}>Cancel</button>
        }
      />
      <ScrollBody>
        {d._scanned && (
          <div style={{
            background: theme.surface, borderRadius: 14, padding: '10px 14px', marginBottom: 12,
            border: `0.5px solid ${theme.border}`,
            display: 'flex', alignItems: 'center', gap: 10,
          }}>
            <Icon name="sparkle" size={16} style={{ color: theme.blue }}/>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13, fontWeight: 600, color: theme.text, letterSpacing: -0.1 }}>
                AI filled these from your photo
              </div>
              <div style={{ fontSize: 11.5, color: theme.textMute, marginTop: 1 }}>
                Yellow = check this one
              </div>
            </div>
          </div>
        )}

        <div style={{
          background: theme.surface, borderRadius: 18, padding: '4px 14px',
          border: `0.5px solid ${theme.border}`,
        }}>
          <ReviewField theme={theme} label="Name" value={d.name} onChange={v => set('name', v)} flag={lowConf('name')}/>
          <ReviewField theme={theme} label="Car" value={d.car} onChange={v => set('car', v)} flag={lowConf('car')}/>
          <ReviewField theme={theme} label="Location" value={d.location} onChange={v => set('location', v)} flag={lowConf('location')}/>
          <ReviewField theme={theme} label="Finance" value={d.finance} onChange={v => set('finance', v)} flag={lowConf('finance')}/>
          <ReviewField theme={theme} label="Notes" value={d.notes} onChange={v => set('notes', v)} flag={lowConf('notes')} multi last/>
        </div>

        <div style={{
          fontSize: 11, fontWeight: 700, letterSpacing: 1, textTransform: 'uppercase',
          color: theme.textMute, padding: '18px 4px 8px',
        }}>Initial status</div>
        <StatusToggle status={d.status} onChange={v => set('status', v)} theme={theme} />

        <button onClick={onSave} disabled={!d.name} style={{
          marginTop: 20, width: '100%', border: 'none',
          padding: '15px 20px', borderRadius: 14,
          background: d.name ? theme.text : theme.chip,
          color: d.name ? theme.bg : theme.textDim,
          fontFamily: 'inherit', fontSize: 15, fontWeight: 600,
          cursor: d.name ? 'pointer' : 'default',
          letterSpacing: -0.15,
        }}>Save customer</button>

        <div style={{ height: 80 }} />
      </ScrollBody>
    </React.Fragment>
  );
}

function ReviewField({ theme, label, value, onChange, flag, multi, last }) {
  return (
    <div style={{
      padding: '10px 0',
      borderBottom: last ? 'none' : `0.5px solid ${theme.border}`,
      position: 'relative',
    }}>
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      }}>
        <div style={{ fontSize: 11, fontWeight: 600, color: theme.textMute, letterSpacing: 0.4, textTransform: 'uppercase' }}>{label}</div>
        {flag && <Chip theme={theme} tone="red">low confidence</Chip>}
      </div>
      {multi ? (
        <textarea value={value} onChange={e => onChange(e.target.value)} rows={3}
          style={{
            width: '100%', border: 'none', resize: 'none', background: 'transparent',
            fontFamily: 'inherit', fontSize: 15, color: theme.text, outline: 'none',
            padding: '4px 0 0', letterSpacing: -0.15, lineHeight: 1.4,
          }}
        />
      ) : (
        <input value={value} onChange={e => onChange(e.target.value)}
          style={{
            width: '100%', border: 'none', background: 'transparent',
            fontFamily: 'inherit', fontSize: 15, color: theme.text, outline: 'none',
            padding: '4px 0 0', letterSpacing: -0.15,
          }}
        />
      )}
    </div>
  );
}

window.AddCaptureScreen = AddCaptureScreen;
