// Add Item — paste URL / upload image → xAI extracts metadata → confirm

// Default "Specific date" picker starting label: next Saturday (Month Day)
function defaultDateLabel() {
  const d = new Date();
  const delta = (6 - d.getDay() + 7) % 7 || 7; // next Saturday
  d.setDate(d.getDate() + delta);
  const dow = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'][d.getDay()];
  const mon = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'][d.getMonth()];
  return `${dow}, ${mon} ${d.getDate()}`;
}

// Maps a URL hostname → a plausible mock detection. A real backend would
// scrape og:metadata; we pick a preset per-platform so the demo feels real.
function mockDetectForHost(host) {
  const presets = {
    'instagram.com': {
      title: 'Little Gem — natural wine bar',
      source: 'instagram.com', category: 'food',
      image: { w: 600, h: 400, palette: ['#FF6B5B','#FFD4C2','#FBF6EE'], pattern: 'wineglass' },
      suggestedNote: 'apparently the skin-contact is unreal',
    },
    'youtube.com': {
      title: 'That weird taxidermy bar in Oakland',
      source: 'youtube.com', category: 'nightlife',
      image: { w: 600, h: 620, palette: ['#1E2A4A','#C58BF2','#FBF6EE'], pattern: 'taxidermy' },
      suggestedNote: 'looks unhinged in the best way',
    },
    'eventbrite.com': {
      title: 'Sunset Cinema — this Friday',
      source: 'eventbrite.com', category: 'movies',
      image: { w: 600, h: 360, palette: ['#E76F51','#F4A261','#1E2A4A'], pattern: 'sunset' },
      suggestedNote: 'bringing the picnic blanket 🌅',
    },
    'songkick.com': {
      title: 'Japanese Breakfast @ The Fillmore',
      source: 'songkick.com', category: 'music',
      image: { w: 600, h: 420, palette: ['#C58BF2','#1E2A4A','#FFD4C2'], pattern: 'concert' },
      suggestedNote: 'got 4 tix — who wants??',
    },
    'alltrails.com': {
      title: 'Mission Trail hike',
      source: 'alltrails.com', category: 'outdoors',
      image: { w: 600, h: 720, palette: ['#8AA896','#2A9D8F','#FBF6EE'], pattern: 'hike' },
      suggestedNote: 'do this before it gets too hot pls',
    },
    'resy.com': {
      title: 'Kindred — pasta tasting menu',
      source: 'resy.com', category: 'food',
      image: { w: 600, h: 540, palette: ['#FF6B5B','#F4A261','#FBF6EE'], pattern: 'pasta' },
      suggestedNote: 'supposedly the move for birthdays',
    },
  };
  if (presets[host]) return presets[host];
  // Fallback: generic activity with a colorful pattern
  return {
    title: `Something from ${host}`,
    source: host, category: 'food',
    image: { w: 600, h: 500, palette: ['#FF6B5B','#FFD4C2','#FBF6EE'], pattern: 'blobs' },
    suggestedNote: '',
  };
}

function hostFromUrl(raw) {
  try { return new URL(raw).host.replace(/^www\./, ''); }
  catch (e) {
    const m = String(raw).match(/^(?:https?:\/\/)?(?:www\.)?([^/\s]+)/i);
    return m ? m[1] : raw;
  }
}

function AddScreen({ onClose, onAdd, extractLink, extractImage }) {
  const [url, setUrl] = React.useState('');
  const [phase, setPhase] = React.useState('empty'); // empty | loading | detected | error
  const [detected, setDetected] = React.useState(null);
  const [category, setCategory] = React.useState(null);
  const [note, setNote] = React.useState('');
  const [whenChoice, setWhenChoice] = React.useState('anytime'); // anytime | dated
  const [pickedStart, setPickedStart] = React.useState(defaultDateLabel());
  const [pickedEnd, setPickedEnd] = React.useState(null);  // null → single day
  const [detectedDate, setDetectedDate] = React.useState(null); // null, or { date, endDate } from scrape
  const [overriding, setOverriding] = React.useState(false);
  const [error, setError] = React.useState(null);
  const [posting, setPosting] = React.useState(false);
  const [clipboardUrl, setClipboardUrl] = React.useState(null);

  const debounceRef = React.useRef(null);
  const fileInputRef = React.useRef(null);
  const cameraInputRef = React.useRef(null);

  const runLink = async (src) => {
    setError(null); setPhase('loading');
    try {
      const d = await extractLink(src);
      // Map server response → client shape
      const det = {
        title: d.title,
        source: d.source || hostFromUrl(src) || 'link',
        url: d.url || src,
        type: d.type,
        category: d.category,
        image: d.image_url ? { url: d.image_url } : null,
        suggestedNote: d.suggested_note || '',
        date: d.date || null, endDate: d.end_date || null,
        time: d.time || null, location: d.location || null,
        via: 'link',
      };
      applyDetected(det);
    } catch (e) {
      setError(e.message || 'extraction failed'); setPhase('error');
    }
  };

  const runImage = async (file) => {
    setError(null); setPhase('loading');
    try {
      const { detected: d } = await extractImage(file);
      const det = {
        title: d.title,
        source: 'Screenshot',
        url: null,
        type: d.type,
        category: d.category,
        image: d.image_url ? { url: d.image_url } : null,
        suggestedNote: d.suggested_note || '',
        date: d.date || null, endDate: d.end_date || null,
        time: d.time || null, location: d.location || null,
        via: 'image',
      };
      applyDetected(det);
    } catch (e) {
      setError(e.message || 'image analysis failed'); setPhase('error');
    }
  };

  // Shared: take a detected object → seed form state
  const applyDetected = (det) => {
    setDetected(det); setCategory(det.category); setNote(det.suggestedNote || '');
    setOverriding(false);
    if (det.type === 'event' && det.date) {
      setWhenChoice('dated');
      setPickedStart(det.date);
      setPickedEnd(det.endDate || null);
      setDetectedDate({ date: det.date, endDate: det.endDate || null });
    } else {
      setWhenChoice('anytime');
      setDetectedDate(null);
    }
    setPhase('detected');
  };

  // URL input: debounce so we don't call the API on every keystroke
  React.useEffect(() => {
    if (debounceRef.current) clearTimeout(debounceRef.current);
    if (!url || url.length < 10 || !/^https?:\/\//i.test(url)) return;
    debounceRef.current = setTimeout(() => runLink(url), 600);
    return () => { if (debounceRef.current) clearTimeout(debounceRef.current); };
    // eslint-disable-next-line
  }, [url]);

  const pasteFromClipboard = async () => {
    try {
      if (!navigator.clipboard?.readText) { setError('clipboard not available — paste manually'); return; }
      const t = (await navigator.clipboard.readText()).trim();
      if (!/^https?:\/\//i.test(t)) { setError('nothing in your clipboard looks like a link'); return; }
      setUrl(t);
    } catch (e) {
      setError('clipboard access blocked — paste manually');
    }
  };

  // Watch clipboard on-screen state — show a clipboard chip if it's a URL
  React.useEffect(() => {
    let active = true;
    const check = async () => {
      try {
        if (!navigator.clipboard?.readText) return;
        const t = (await navigator.clipboard.readText()).trim();
        if (active && /^https?:\/\//i.test(t)) setClipboardUrl(t);
      } catch {}
    };
    check();
    return () => { active = false; };
  }, []);

  const clear = () => {
    if (debounceRef.current) clearTimeout(debounceRef.current);
    setUrl(''); setPhase('empty'); setDetected(null); setCategory(null); setNote(''); setError(null);
  };

  const onPickFile = (e) => {
    const f = e.target.files?.[0];
    if (!f) return;
    runImage(f);
  };

  // Build the real item from the detected object + user choices
  const buildItem = () => {
    if (!detected) return null;
    const cat = category || detected.category;
    const base = {
      title: detected.title,
      source: detected.source,
      url: detected.url || url || null,
      category: cat,
      image: detected.image,
      note: note || undefined,
      location: detected.location || undefined,
    };
    if (whenChoice === 'dated') {
      return {
        ...base,
        type: 'event',
        date: pickedStart,
        endDate: pickedEnd || undefined,
        time: detected.time || undefined,
      };
    }
    return { ...base, type: 'activity' };
  };

  const submit = async () => {
    const item = buildItem();
    if (!item) return;
    setPosting(true);
    try { await onAdd(item); }
    catch (e) { setError(e.message || 'could not post'); setPosting(false); }
  };
  const postDisabled = phase !== 'detected' || posting;

  return (
    <div style={{ background: C.cream, minHeight: '100%', paddingBottom: 40 }}>
      {/* custom header: Cancel | title | Add */}
      <div style={{
        padding: 'calc(env(safe-area-inset-top, 12px) + 18px) 16px 10px',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      }}>
        <button onClick={onClose} style={{
          background: 'transparent', border: 'none',
          color: C.inkMuted, fontFamily: '"DM Sans",system-ui',
          fontSize: 15, fontWeight: 500, cursor: 'pointer', padding: 4,
        }}>Cancel</button>
        <div style={{
          fontFamily: '"DM Sans", system-ui',
          fontSize: 15, fontWeight: 600, color: C.navy,
        }}>Add to Flock</div>
        <button
          disabled={postDisabled}
          onClick={submit}
          style={{
            background: !postDisabled ? C.coral : 'transparent',
            color: !postDisabled ? '#fff' : C.inkMuted,
            border: 'none', borderRadius: 999,
            padding: '7px 14px',
            fontFamily: '"DM Sans",system-ui',
            fontSize: 14, fontWeight: 700, cursor: !postDisabled ? 'pointer' : 'default',
            opacity: !postDisabled ? 1 : 0.5,
          }}>{posting ? 'Posting…' : 'Post'}</button>
      </div>

      {/* URL input area */}
      <div style={{ padding: '12px 16px 0' }}>
        <div style={{
          background: C.white,
          borderRadius: 20,
          padding: 14,
          boxShadow: '0 1px 3px rgba(30,42,74,0.04), 0 6px 16px rgba(30,42,74,0.04)',
        }}>
          <div style={{
            fontFamily: '"DM Sans",system-ui', fontSize: 11.5,
            fontWeight: 700, color: C.inkMuted,
            letterSpacing: 1, textTransform: 'uppercase',
            marginBottom: 8,
          }}>Paste a link</div>
          <div style={{
            display: 'flex', alignItems: 'center', gap: 10,
            background: C.cream, borderRadius: 14, padding: '10px 12px',
          }}>
            <svg width="17" height="17" viewBox="0 0 17 17" fill="none" style={{ color: C.inkMuted, flexShrink: 0 }}>
              <path d="M7 10L10 7M6 4.5l1.5-1.5a3 3 0 014.2 4.2L10 8.8M11 7l-1.5 1.5M7 9.7l-1.5 1.5a3 3 0 01-4.2-4.2L3 5.4" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/>
            </svg>
            <input
              value={url}
              onChange={e => setUrl(e.target.value)}
              onPaste={(e) => {
                // Immediate detect on paste (no debounce wait)
                const v = (e.clipboardData?.getData('text') || '').trim();
                if (/^https?:\/\//i.test(v)) { setUrl(v); runLink(v); e.preventDefault(); }
              }}
              placeholder="https://..."
              autoCapitalize="none"
              autoCorrect="off"
              spellCheck={false}
              type="url"
              style={{
                flex: 1, border: 'none', background: 'transparent', outline: 'none',
                fontFamily: '"DM Sans",system-ui', fontSize: 15, color: C.navy,
                minWidth: 0,
              }}
            />
            {url && (
              <button onClick={clear} style={{
                background: 'transparent', border: 'none', cursor: 'pointer',
                color: C.inkMuted, padding: 4, display: 'flex',
              }}>
                <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
                  <circle cx="7" cy="7" r="6.5" fill="rgba(30,42,74,0.15)"/>
                  <path d="M4.5 4.5l5 5M9.5 4.5l-5 5" stroke="#fff" strokeWidth="1.6" strokeLinecap="round"/>
                </svg>
              </button>
            )}
          </div>

          {/* clipboard suggestion — only shown when clipboard holds a URL */}
          {phase === 'empty' && clipboardUrl && (
            <button onClick={() => { setUrl(clipboardUrl); runLink(clipboardUrl); }} style={{
              display: 'flex', alignItems: 'center', gap: 10,
              width: '100%', marginTop: 12,
              padding: '10px 12px',
              borderRadius: 12,
              border: `1.2px solid ${C.coral}`,
              background: 'rgba(255,107,91,0.06)',
              cursor: 'pointer', textAlign: 'left',
            }}>
              <SourceDot source={hostFromUrl(clipboardUrl) || 'link'}/>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{
                  fontFamily: '"DM Sans",system-ui', fontSize: 11, fontWeight: 700,
                  color: C.coral, letterSpacing: 0.6, textTransform: 'uppercase',
                }}>From your clipboard</div>
                <div style={{
                  fontFamily: '"DM Sans",system-ui', fontSize: 13, color: C.navy,
                  whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
                  marginTop: 1,
                }}>{hostFromUrl(clipboardUrl)}{new URL(clipboardUrl).pathname.slice(0, 30)}</div>
              </div>
              <div style={{
                fontFamily: '"DM Sans",system-ui', fontSize: 12, fontWeight: 700,
                color: C.coral, flexShrink: 0,
              }}>Paste →</div>
            </button>
          )}
          {phase === 'empty' && !clipboardUrl && (
            <button onClick={pasteFromClipboard} style={{
              display: 'flex', alignItems: 'center', gap: 10, justifyContent: 'center',
              width: '100%', marginTop: 12,
              padding: '10px 12px',
              borderRadius: 12,
              border: `1.2px solid ${C.hairline}`,
              background: C.cream,
              cursor: 'pointer', color: C.navy,
              fontFamily: '"DM Sans",system-ui', fontSize: 13, fontWeight: 600,
            }}>
              <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
                <path d="M4 2h6v2H4zM3 4h8v8H3z" stroke="currentColor" strokeWidth="1.3" fill="none"/>
              </svg>
              Paste link from clipboard
            </button>
          )}
        </div>

        {/* divider */}
        {phase === 'empty' && (
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, margin: '14px 4px' }}>
            <div style={{ flex: 1, height: 1, background: 'rgba(30,42,74,0.1)' }}/>
            <div style={{
              fontFamily: '"DM Sans",system-ui', fontSize: 11,
              fontWeight: 700, color: C.inkMuted,
              letterSpacing: 1.5, textTransform: 'uppercase',
            }}>or</div>
            <div style={{ flex: 1, height: 1, background: 'rgba(30,42,74,0.1)' }}/>
          </div>
        )}

        {/* Screenshot / image upload */}
        {phase === 'empty' && (
          <div style={{
            background: C.white, borderRadius: 20, padding: 14,
            boxShadow: '0 1px 3px rgba(30,42,74,0.04), 0 6px 16px rgba(30,42,74,0.04)',
          }}>
            <div style={{
              fontFamily: '"DM Sans",system-ui', fontSize: 11.5,
              fontWeight: 700, color: C.inkMuted,
              letterSpacing: 1, textTransform: 'uppercase',
              marginBottom: 8,
            }}>Upload a screenshot</div>
            <input ref={fileInputRef} type="file" accept="image/*" onChange={onPickFile}
                   style={{ display: 'none' }}/>
            <input ref={cameraInputRef} type="file" accept="image/*" capture="environment" onChange={onPickFile}
                   style={{ display: 'none' }}/>
            <div style={{ display: 'flex', gap: 10 }}>
              <button onClick={() => fileInputRef.current?.click()} style={{
                flex: 1, height: 92, borderRadius: 14,
                border: `1.5px dashed ${C.coral}`,
                background: 'rgba(255,107,91,0.06)',
                color: C.coral, cursor: 'pointer',
                display: 'flex', flexDirection: 'column',
                alignItems: 'center', justifyContent: 'center', gap: 6,
                fontFamily: '"DM Sans",system-ui',
                fontSize: 12.5, fontWeight: 600, padding: 0,
              }}>
                <svg width="22" height="22" viewBox="0 0 22 22" fill="none">
                  <rect x="3" y="3" width="16" height="16" rx="3" stroke="currentColor" strokeWidth="1.6"/>
                  <path d="M3 14l4-4 4 4 3-3 5 5" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round" fill="none"/>
                  <circle cx="14" cy="8" r="1.5" fill="currentColor"/>
                </svg>
                Photo library
              </button>
              <button onClick={() => cameraInputRef.current?.click()} style={{
                flex: 1, height: 92, borderRadius: 14,
                border: `1.5px solid ${C.hairline}`,
                background: C.cream, color: C.navy, cursor: 'pointer',
                display: 'flex', flexDirection: 'column',
                alignItems: 'center', justifyContent: 'center', gap: 6,
                fontFamily: '"DM Sans",system-ui',
                fontSize: 12.5, fontWeight: 600, padding: 0,
              }}>
                <svg width="22" height="22" viewBox="0 0 22 22" fill="none">
                  <rect x="3" y="5" width="16" height="13" rx="2.5" stroke="currentColor" strokeWidth="1.6"/>
                  <circle cx="11" cy="11.5" r="3.3" stroke="currentColor" strokeWidth="1.6"/>
                  <path d="M8 5l1-1.5h4L14 5" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round"/>
                </svg>
                Take a photo
              </button>
            </div>
            <div style={{
              marginTop: 10,
              display: 'flex', alignItems: 'center', gap: 8,
              padding: '8px 10px', borderRadius: 10,
              background: 'rgba(138,168,150,0.12)',
            }}>
              <svg width="14" height="14" viewBox="0 0 14 14" fill="none" style={{ flexShrink: 0 }}>
                <circle cx="7" cy="7" r="6" stroke={C.sage} strokeWidth="1.4"/>
                <path d="M4.5 7l1.8 1.8L10 5" stroke={C.sage} strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" fill="none"/>
              </svg>
              <div style={{
                fontFamily: '"DM Sans",system-ui', fontSize: 11.5,
                color: C.sage, fontWeight: 600, letterSpacing: -0.05,
              }}>
                we'll read text in the image to pull title, date & category
              </div>
            </div>
          </div>
        )}
      </div>

      {/* Error state */}
      {phase === 'error' && (
        <div style={{
          margin: '14px 16px 0',
          background: C.white, borderRadius: 20, padding: 16,
          boxShadow: '0 1px 3px rgba(30,42,74,0.04)',
        }}>
          <div style={{ fontFamily: '"DM Sans",system-ui', fontWeight: 600, color: C.coralDeep, marginBottom: 4 }}>
            {error || 'Extraction failed'}
          </div>
          <div style={{ fontFamily: '"DM Sans",system-ui', fontSize: 13, color: C.inkMuted }}>
            You can still post it manually — tap Post with what you've got.
          </div>
          <button onClick={clear} style={{
            marginTop: 10, height: 36, padding: '0 14px', borderRadius: 999,
            background: C.navy, color: C.cream, border: 'none',
            fontFamily: '"DM Sans",system-ui', fontSize: 13, fontWeight: 600,
            cursor: 'pointer',
          }}>Start over</button>
        </div>
      )}

      {/* Loading state */}
      {phase === 'loading' && (
        <div style={{
          margin: '14px 16px 0',
          background: C.white, borderRadius: 20, padding: '20px 16px',
          display: 'flex', alignItems: 'center', gap: 14,
          boxShadow: '0 1px 3px rgba(30,42,74,0.04), 0 6px 16px rgba(30,42,74,0.04)',
        }}>
          <div style={{
            width: 48, height: 48, borderRadius: 14,
            background: C.cream,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <div style={{
              width: 22, height: 22, borderRadius: '50%',
              border: `2.5px solid ${C.coralSoft}`,
              borderTopColor: C.coral,
              animation: 'spin 700ms linear infinite',
            }}/>
            <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: '"DM Sans",system-ui', fontWeight: 600, fontSize: 15, color: C.navy }}>
              Reading link…
            </div>
            <div style={{ fontFamily: '"DM Sans",system-ui', fontSize: 12.5, color: C.inkMuted, marginTop: 2 }}>
              pulling title, photo, and details
            </div>
          </div>
        </div>
      )}

      {/* Detected card */}
      {phase === 'detected' && detected && (
        <div style={{ padding: '14px 16px 0' }}>
          <div style={{
            background: C.white, borderRadius: 20, padding: 14,
            boxShadow: '0 1px 3px rgba(30,42,74,0.04), 0 6px 16px rgba(30,42,74,0.04)',
          }}>
            <div style={{
              display: 'flex', alignItems: 'center', gap: 6,
              fontFamily: '"DM Sans",system-ui', fontSize: 11.5,
              color: C.sage, fontWeight: 700, letterSpacing: 1,
              textTransform: 'uppercase', marginBottom: 10,
            }}>
              <svg width="13" height="13" viewBox="0 0 13 13" fill="none">
                <circle cx="6.5" cy="6.5" r="5.5" fill={C.sage}/>
                <path d="M3.8 6.8l2 2 3.5-4" stroke="#fff" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" fill="none"/>
              </svg>
              {detected.via === 'image' ? 'Detected from screenshot' : 'Detected from link'}
            </div>
            <div style={{ display: 'flex', gap: 12 }}>
              <Placeholder spec={detected.image} radius={12} style={{ width: 78, height: 78, flexShrink: 0 }}/>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{
                  fontFamily: '"DM Sans",system-ui', fontWeight: 600,
                  fontSize: 15, color: C.navy, letterSpacing: -0.2, lineHeight: 1.3,
                }}>{detected.title}</div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 5, marginTop: 5 }}>
                  <SourceDot source={detected.source}/>
                  <span style={{ fontFamily: '"DM Sans",system-ui', fontSize: 12, color: C.inkMuted }}>
                    {detected.source}
                  </span>
                </div>
              </div>
            </div>
          </div>

          {/* Category row — auto-detected highlighted */}
          <div style={{ marginTop: 16 }}>
            <div style={{
              padding: '0 4px 8px',
              fontFamily: '"DM Sans",system-ui', fontSize: 11.5,
              fontWeight: 700, color: C.inkMuted,
              letterSpacing: 1, textTransform: 'uppercase',
            }}>Category · auto-detected</div>
            <div style={{ display: 'flex', gap: 7, overflowX: 'auto', paddingBottom: 4 }}>
              {CATEGORIES.slice(1).map(c => {
                const on = c.id === (category || detected.category);
                return (
                  <button key={c.id} onClick={() => setCategory(c.id)} style={{
                    display: 'inline-flex', alignItems: 'center', gap: 5,
                    height: 36, padding: '0 13px 0 11px', borderRadius: 999,
                    background: on ? C.coral : C.white,
                    color: on ? C.white : C.navy,
                    border: `1.5px solid ${on ? C.coral : 'rgba(30,42,74,0.1)'}`,
                    fontFamily: '"DM Sans",system-ui',
                    fontWeight: 600, fontSize: 13,
                    flexShrink: 0,
                    cursor: 'pointer',
                  }}>
                    <span style={{ fontSize: 14 }}>{c.emoji}</span>
                    {c.label}
                  </button>
                );
              })}
            </div>
          </div>

          {/* When — anytime vs dated. When a date was auto-detected, surface
              it inline with an "Override" affordance; tapping reveals the
              range picker. Open-ended sources default to "Anytime" with a
              "Pick a date" option. */}
          <div style={{ marginTop: 18 }}>
            <div style={{
              padding: '0 4px 8px',
              fontFamily: '"DM Sans",system-ui', fontSize: 11.5,
              fontWeight: 700, color: C.inkMuted,
              letterSpacing: 1, textTransform: 'uppercase',
            }}>When</div>

            {detectedDate && whenChoice === 'dated' && !overriding ? (
              <div style={{
                background: C.white, borderRadius: 14, padding: 14,
                display: 'flex', alignItems: 'center', gap: 12,
                boxShadow: '0 1px 3px rgba(30,42,74,0.04)',
              }}>
                <div style={{
                  width: 50, textAlign: 'center',
                  background: C.coralSoft, borderRadius: 10, padding: '6px 0',
                }}>
                  <div style={{ fontFamily: '"DM Sans",system-ui', fontSize: 10, fontWeight: 700, color: C.coralDeep, letterSpacing: 0.6 }}>
                    {detectedDate.date.split(',')[0].toUpperCase()}
                  </div>
                  <div style={{ fontFamily: '"Instrument Serif",serif', fontStyle: 'italic', fontSize: 22, lineHeight: 1, color: C.navy }}>
                    {detectedDate.date.split(' ').pop()}
                    {detectedDate.endDate ? '→' + detectedDate.endDate.split(' ').pop() : ''}
                  </div>
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontFamily: '"DM Sans",system-ui', fontWeight: 600, fontSize: 13.5, color: C.navy }}>
                    {detectedDate.endDate ? dateRangeLabel(detectedDate.date, detectedDate.endDate) : detectedDate.date}
                    {detected?.time && <> · {detected.time}</>}
                  </div>
                  <div style={{ fontFamily: '"DM Sans",system-ui', fontSize: 11.5, color: C.sage, fontWeight: 600, marginTop: 2 }}>
                    ✓ from the {detected?.via === 'image' ? 'screenshot' : 'event page'}
                  </div>
                </div>
                <button onClick={() => setOverriding(true)} style={{
                  background: 'transparent', border: 'none', cursor: 'pointer',
                  padding: 6, display: 'flex', alignItems: 'center', gap: 4,
                  color: C.navy, fontFamily: '"DM Sans",system-ui', fontSize: 12, fontWeight: 600,
                }}>
                  <svg width="12" height="12" viewBox="0 0 16 16"><path d="M10 3l3 3-7 7H3v-3z M9 4l3 3" stroke={C.navy} strokeWidth="1.5" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
                  Override
                </button>
              </div>
            ) : (
              <>
                <div style={{
                  display: 'flex', background: C.white,
                  borderRadius: 14, padding: 4,
                  boxShadow: '0 1px 3px rgba(30,42,74,0.04)',
                }}>
                  {[
                    { id: 'anytime', label: 'Anytime — on the Board' },
                    { id: 'dated',   label: 'Pick a date' },
                  ].map(o => {
                    const on = whenChoice === o.id;
                    return (
                      <button key={o.id} onClick={() => setWhenChoice(o.id)} style={{
                        flex: 1, height: 36, borderRadius: 10,
                        background: on ? C.navy : 'transparent',
                        color: on ? C.cream : C.navy,
                        border: 'none', cursor: 'pointer',
                        fontFamily: '"DM Sans",system-ui',
                        fontSize: 12.5, fontWeight: 600,
                        letterSpacing: -0.1,
                      }}>{o.label}</button>
                    );
                  })}
                </div>
                {whenChoice === 'dated' && (
                  <DateRangePicker start={pickedStart} end={pickedEnd}
                    onChange={(s, e) => { setPickedStart(s); setPickedEnd(e); }}/>
                )}
                {whenChoice === 'anytime' && !detected?.date && (
                  <div style={{
                    marginTop: 10, padding: '10px 12px',
                    background: 'rgba(138,168,150,0.12)', borderRadius: 10,
                    fontFamily: '"DM Sans",system-ui', fontSize: 12,
                    color: C.sage, fontWeight: 600, lineHeight: 1.4,
                  }}>
                    sits on the Board as an idea. the group can propose dates later.
                  </div>
                )}
              </>
            )}
          </div>

          {/* Note */}
          <div style={{ marginTop: 18 }}>
            <div style={{
              padding: '0 4px 8px',
              fontFamily: '"DM Sans",system-ui', fontSize: 11.5,
              fontWeight: 700, color: C.inkMuted,
              letterSpacing: 1, textTransform: 'uppercase',
            }}>Note for the group</div>
            <textarea
              value={note}
              onChange={e => setNote(e.target.value)}
              placeholder="say something…"
              rows={2}
              style={{
                width: '100%', boxSizing: 'border-box',
                background: C.white, border: 'none', borderRadius: 14,
                padding: '12px 14px', resize: 'none',
                fontFamily: '"DM Sans",system-ui', fontSize: 14, color: C.navy,
                outline: 'none',
                boxShadow: '0 1px 3px rgba(30,42,74,0.04)',
              }}
            />
          </div>
        </div>
      )}
    </div>
  );
}

// ─── Date range picker — supports single-day + multi-day events.
// Tap a day to set start; tap a later day to extend the range; tap an
// earlier day (or the same day) to reset to a single-day selection.
function DateRangePicker({ start, end, onChange, allowRange = true }) {
  const today = new Date();
  const [viewYear, setViewYear] = React.useState(today.getFullYear());
  const [viewMonth, setViewMonth] = React.useState(today.getMonth());
  const startDate = labelToDate(start, viewYear);
  const endDate = end ? labelToDate(end, viewYear) : null;

  const first = new Date(viewYear, viewMonth, 1);
  const lead = first.getDay();
  const total = new Date(viewYear, viewMonth + 1, 0).getDate();
  const cells = [...Array(lead).fill(null), ...Array.from({ length: total }, (_, i) => i + 1)];
  const monthLabel = first.toLocaleString('en-US', { month: 'long', year: 'numeric' });
  const days = ['S','M','T','W','T','F','S'];

  const pick = (day) => {
    const picked = new Date(viewYear, viewMonth, day);
    const label = dateLabel(picked);
    if (!startDate) { onChange(label, null); return; }
    if (!allowRange) { onChange(label, null); return; }
    if (!endDate) {
      if (picked > startDate) onChange(start, label);
      else onChange(label, null);
    } else {
      // Third tap: reset range to just this day
      onChange(label, null);
    }
  };
  const isInRange = (day) => {
    if (!startDate) return false;
    const d = new Date(viewYear, viewMonth, day);
    if (!endDate) return d.getTime() === startDate.getTime();
    return d.getTime() >= startDate.getTime() && d.getTime() <= endDate.getTime();
  };
  const isEndpoint = (day) => {
    const d = new Date(viewYear, viewMonth, day);
    if (startDate && d.getTime() === startDate.getTime()) return 'start';
    if (endDate && d.getTime() === endDate.getTime()) return 'end';
    return null;
  };

  return (
    <div style={{
      marginTop: 10, background: C.white, borderRadius: 18, padding: 14,
      boxShadow: '0 1px 3px rgba(30,42,74,0.04)',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
        <div style={{ fontFamily: '"Instrument Serif", serif', fontStyle: 'italic', fontSize: 22, color: C.navy }}>
          {monthLabel}
        </div>
        <div style={{ display: 'flex', gap: 6 }}>
          <button onClick={() => { const m = viewMonth - 1; if (m < 0) { setViewMonth(11); setViewYear(y => y - 1); } else setViewMonth(m); }}
            style={navBtnStyle}>‹</button>
          <button onClick={() => { const m = viewMonth + 1; if (m > 11) { setViewMonth(0); setViewYear(y => y + 1); } else setViewMonth(m); }}
            style={navBtnStyle}>›</button>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 2 }}>
        {days.map((d, i) => (
          <div key={i} style={{
            textAlign: 'center', fontFamily: '"DM Sans",system-ui',
            fontSize: 10.5, fontWeight: 700, color: C.inkMuted,
            letterSpacing: 0.5, padding: '4px 0',
          }}>{d}</div>
        ))}
        {cells.map((d, i) => {
          if (d === null) return <div key={i}/>;
          const inRange = isInRange(d);
          const ep = isEndpoint(d);
          return (
            <button key={i} onClick={() => pick(d)} style={{
              height: 34, border: 'none',
              background: ep ? C.coral : (inRange ? 'rgba(255,107,91,0.18)' : 'transparent'),
              color: ep ? '#fff' : C.navy,
              borderRadius: ep === 'start' ? '10px 3px 3px 10px'
                          : ep === 'end'   ? '3px 10px 10px 3px'
                          : inRange ? 3 : 10,
              cursor: 'pointer',
              fontFamily: '"DM Sans",system-ui',
              fontSize: 13.5, fontWeight: ep ? 700 : 500,
            }}>{d}</button>
          );
        })}
      </div>

      <div style={{
        marginTop: 10, display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '8px 10px', borderRadius: 10, background: C.cream,
      }}>
        <div style={{ fontFamily: '"DM Sans",system-ui', fontSize: 12.5, color: C.navy }}>
          {end
            ? <><b>{dateRangeLabel(start, end)}</b> · {daysBetween(start, end)} days</>
            : <b>{start}</b>}
        </div>
        {end && (
          <button onClick={() => onChange(start, null)} style={{
            background: 'transparent', border: 'none', color: C.inkMuted,
            fontFamily: '"DM Sans",system-ui', fontSize: 12, fontWeight: 600, cursor: 'pointer',
          }}>Single day</button>
        )}
        {!end && (
          <div style={{ fontFamily: '"DM Sans",system-ui', fontSize: 11.5, color: C.inkMuted }}>
            tap a later day for a range
          </div>
        )}
      </div>
    </div>
  );
}

const navBtnStyle = {
  width: 28, height: 28, borderRadius: 8,
  background: C.cream, border: 'none', cursor: 'pointer',
  display: 'flex', alignItems: 'center', justifyContent: 'center',
  fontFamily: '"DM Sans",system-ui', fontWeight: 600, color: C.navy, fontSize: 15,
};

// Convert "Sat, Apr 26" → Date (uses viewYear since label has no year)
function labelToDate(label, year) {
  if (!label) return null;
  const m = String(label).match(/([A-Za-z]{3,}),?\s*([A-Za-z]{3,})\s*(\d{1,2})/);
  if (!m) return null;
  const monIdx = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
    .findIndex(mm => m[2].slice(0,3).toLowerCase() === mm.toLowerCase());
  if (monIdx < 0) return null;
  return new Date(year, monIdx, parseInt(m[3], 10));
}
function dateLabel(d) {
  const dow = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'][d.getDay()];
  const mon = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'][d.getMonth()];
  return `${dow}, ${mon} ${d.getDate()}`;
}
function dateRangeLabel(start, end) {
  if (!end) return start;
  const sD = labelToDate(start, new Date().getFullYear());
  const eD = labelToDate(end, new Date().getFullYear());
  if (!sD || !eD) return `${start} → ${end}`;
  const mon = (d) => ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'][d.getMonth()];
  if (sD.getMonth() === eD.getMonth()) return `${mon(sD)} ${sD.getDate()}–${eD.getDate()}`;
  return `${mon(sD)} ${sD.getDate()} → ${mon(eD)} ${eD.getDate()}`;
}
function daysBetween(start, end) {
  const sD = labelToDate(start, new Date().getFullYear());
  const eD = labelToDate(end, new Date().getFullYear());
  if (!sD || !eD) return 1;
  return Math.round((eD - sD) / (1000 * 60 * 60 * 24)) + 1;
}

Object.assign(window, { AddScreen, DateRangePicker, dateRangeLabel, daysBetween, labelToDate, dateLabel });
