// Modal sheets: Quick Add, Paywall premium card

// ─── Quick Add bottom sheet ───────────────────────────────────────
function QuickAddSheet({ isOpen, onClose, onAdd, isDark }) {
  const [title, setTitle] = useState('');
  const [priority, setPriority] = useState('p4');
  const inputRef = useRef(null);

  useEffect(() => {
    if (isOpen) {
      setTimeout(() => inputRef.current?.focus(), 250);
      setTitle('');
      setPriority('p4');
    }
  }, [isOpen]);

  if (!isOpen) return null;

  const fg1 = isDark ? '#EDEDED' : '#121316';
  const fg2 = isDark ? '#71747A' : '#8A8D93';
  const surface = isDark ? '#111112' : '#FAFAFA';
  const surfaceAlt = isDark ? '#1A1A1C' : '#FFFFFF';
  const divider = isDark ? '#1F1F22' : '#EBEBEB';
  const accent = isDark ? '#8B6FFF' : '#4D21FC';

  // Parse highlights from natural-language input
  const highlights = parseNLP(title);
  const detectedTime = highlights.find(h => h.type === 'time');
  const detectedDate = highlights.find(h => h.type === 'date');

  const confirm = () => {
    if (!title.trim()) return;
    onAdd({
      id: Date.now(),
      title: title.trim(),
      priority,
      done: false,
      quadrantColor: { p1: '#EF4444', p2: '#F59E0B', p3: '#4D21FC', p4: '#8A8D93' }[priority],
      meta: [
        detectedDate && { label: detectedDate.label, color: detectedDate.label.match(/today/i) ? '#F59E0B' : undefined },
        detectedTime && { icon: 'schedule', label: detectedTime.label },
      ].filter(Boolean),
    });
  };

  const Chip = ({ icon, label, active, onClick, color }) => (
    <Tap onClick={onClick} scale={0.95} style={{
      display: 'inline-flex', alignItems: 'center', gap: 6,
      padding: '8px 14px', borderRadius: 9999,
      background: active ? (color || accent) : surfaceAlt,
      color: active ? 'white' : fg1,
      border: `1px solid ${active ? (color || accent) : divider}`,
      fontSize: 13, fontWeight: active ? 600 : 500,
      whiteSpace: 'nowrap',
    }}>
      {icon && <Icon name={icon} size={14} color={active ? 'white' : fg2} />}
      {label}
    </Tap>
  );

  return (
    <div style={{
      position: 'absolute', inset: 0,
      background: 'rgba(0,0,0,0.45)',
      display: 'flex', alignItems: 'flex-end', justifyContent: 'center',
      zIndex: 50,
      animation: 'nawiFade 250ms ease-out',
    }} onClick={onClose}>
      <div onClick={(e) => e.stopPropagation()} style={{
        width: '100%',
        background: surface,
        borderRadius: '20px 20px 0 0',
        border: isDark ? `1px solid ${divider}` : 'none',
        borderBottom: 'none',
        paddingBottom: 20,
        animation: 'nawiSlideUp 350ms cubic-bezier(0.215,0.610,0.355,1)',
      }}>
        <SheetHeader
          title="Add task"
          onCancel={onClose}
          onConfirm={confirm}
          confirmDisabled={!title.trim()}
          isDark={isDark}
        />

        {/* Title field with inline NLP highlights */}
        <div style={{
          margin: '4px 16px 12px',
          background: surfaceAlt,
          border: `1px solid ${divider}`,
          borderRadius: 12,
          padding: '14px 16px',
          position: 'relative',
        }}>
          {/* Highlighted overlay */}
          <div aria-hidden style={{
            position: 'absolute', top: 14, left: 16, right: 16, bottom: 14,
            pointerEvents: 'none',
            fontSize: 15, lineHeight: 1.4, color: 'transparent',
            whiteSpace: 'pre-wrap', wordBreak: 'break-word',
          }}>
            {renderHighlighted(title, highlights)}
          </div>
          <input
            ref={inputRef}
            value={title}
            onChange={(e) => setTitle(e.target.value)}
            placeholder="Coffee with Layla tomorrow at 9"
            style={{
              width: '100%', border: 0, outline: 0,
              background: 'transparent',
              fontFamily: 'Cairo, system-ui, sans-serif',
              fontSize: 15, lineHeight: 1.4,
              color: fg1, position: 'relative', zIndex: 1,
            }}
          />
        </div>

        {/* Inline parse summary */}
        {highlights.length > 0 && (
          <div style={{
            margin: '0 16px 12px',
            display: 'flex', flexWrap: 'wrap', gap: 6,
            fontSize: 12, color: fg2,
          }}>
            {highlights.map((h, i) => (
              <span key={i} style={{
                background: HIGHLIGHT_COLOR[h.type] || '#8A8D93',
                color: 'white',
                padding: '2px 8px', borderRadius: 6,
                fontWeight: 600, fontSize: 11,
              }}>{h.type}: {h.label}</span>
            ))}
          </div>
        )}

        {/* Priority chips */}
        <div style={{
          padding: '0 16px 8px',
          display: 'flex', gap: 8, overflowX: 'auto',
        }}>
          <Chip icon="flag" label="Urgent"  active={priority === 'p1'} onClick={() => setPriority('p1')} color="#EF4444" />
          <Chip icon="flag" label="High"    active={priority === 'p2'} onClick={() => setPriority('p2')} color="#F59E0B" />
          <Chip icon="flag" label="Medium"  active={priority === 'p3'} onClick={() => setPriority('p3')} color={accent} />
          <Chip icon="flag" label="Low"     active={priority === 'p4'} onClick={() => setPriority('p4')} color="#8A8D93" />
        </div>

        {/* Metadata strip */}
        <div style={{
          padding: '4px 16px 0',
          display: 'flex', gap: 8, overflowX: 'auto',
        }}>
          <Chip icon="schedule"    label={detectedTime ? detectedTime.label : 'Time'} active={!!detectedTime} color={accent} />
          <Chip icon="calendar_today" label={detectedDate ? detectedDate.label : 'Date'} active={!!detectedDate} color={accent} />
          <Chip icon="folder_open" label="Personal" onClick={() => {}} />
          <Chip icon="label"       label="Add label" onClick={() => {}} />
          <Chip icon="notifications" label="Remind" onClick={() => {}} />
        </div>
      </div>
    </div>
  );
}

// ─── NLP highlight palette (mirrors HighlightTextEditingController) ─
const HIGHLIGHT_COLOR = {
  date: '#00D084', time: '#F59E0B', priority: '#EF4444',
  project: '#0EA5E9', label: '#6A42FF', reminder: '#38BDF8',
  duration: '#00E676',
};

// Minimal NLP — finds day words, "at HH", and a couple priority cues
function parseNLP(text) {
  const t = text.toLowerCase();
  const out = [];
  const dayWords = ['today', 'tomorrow', 'tonight', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];
  dayWords.forEach(w => {
    const i = t.indexOf(w);
    if (i >= 0) out.push({ type: 'date', start: i, end: i + w.length, label: w[0].toUpperCase() + w.slice(1) });
  });
  // "at 9", "at 9pm", "at 14:30"
  const timeRe = /at\s+(\d{1,2})(?::(\d{2}))?\s*(am|pm)?/i;
  const tm = text.match(timeRe);
  if (tm) {
    const hh = tm[1]; const mm = tm[2] || '00';
    const ampm = tm[3] ? tm[3].toLowerCase() : '';
    out.push({ type: 'time', start: tm.index, end: tm.index + tm[0].length, label: `${hh}:${mm}${ampm ? ' ' + ampm : ''}` });
  }
  // "بعد المغرب" — Saudi prayer-time NLP
  const mag = text.indexOf('بعد المغرب');
  if (mag >= 0) out.push({ type: 'reminder', start: mag, end: mag + 10, label: 'بعد المغرب' });
  // "p1".."p4"
  const pri = text.match(/\bp([1-4])\b/i);
  if (pri) out.push({ type: 'priority', start: pri.index, end: pri.index + 2, label: pri[0].toUpperCase() });
  // Sort by start
  return out.sort((a, b) => a.start - b.start);
}

function renderHighlighted(text, highlights) {
  if (!highlights.length) return text;
  const out = [];
  let cur = 0;
  highlights.forEach((h, i) => {
    if (cur < h.start) out.push(<span key={`p${i}`}>{text.slice(cur, h.start)}</span>);
    out.push(
      <span key={`h${i}`} style={{
        background: HIGHLIGHT_COLOR[h.type] || '#8A8D93',
        color: 'white', fontWeight: 600,
        padding: '0 2px', borderRadius: 3,
      }}>{text.slice(h.start, h.end)}</span>
    );
    cur = h.end;
  });
  if (cur < text.length) out.push(<span key="end">{text.slice(cur)}</span>);
  return out;
}

// ─── Paywall premium card overlay ─────────────────────────────────
function PaywallOverlay({ isOpen, onClose, isDark }) {
  if (!isOpen) return null;
  return (
    <div style={{
      position: 'absolute', inset: 0,
      background: isDark
        ? 'radial-gradient(120% 80% at 50% 100%, rgba(106,66,255,0.22) 0%, rgba(0,0,0,0.55) 60%)'
        : 'rgba(255,255,255,0.45)',
      backdropFilter: 'blur(14px)',
      WebkitBackdropFilter: 'blur(14px)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: 24,
      zIndex: 60,
      animation: 'nawiFade 250ms ease-out',
    }} onClick={onClose}>
      <div onClick={(e) => e.stopPropagation()} style={{
        width: '100%', maxWidth: 320,
        background: isDark ? 'rgba(17,17,18,0.92)' : 'rgba(255,255,255,0.94)',
        border: `1px solid ${isDark ? 'rgba(106,66,255,0.28)' : 'rgba(77,33,252,0.18)'}`,
        borderRadius: 28,
        padding: '32px 24px 24px',
        textAlign: 'center',
        boxShadow: isDark
          ? '0 16px 40px rgba(106,66,255,0.22), 0 8px 24px rgba(0,0,0,0.45)'
          : '0 16px 40px rgba(77,33,252,0.14), 0 8px 24px rgba(0,0,0,0.08)',
        animation: 'nawiPaywallIn 320ms cubic-bezier(0.215,0.610,0.355,1)',
      }}>
        <div style={{
          width: 64, height: 64, margin: '0 auto',
          borderRadius: 18,
          background: isDark ? 'rgba(106,66,255,0.18)' : '#F0ECFF',
          border: `1px solid ${isDark ? 'rgba(106,66,255,0.28)' : 'rgba(77,33,252,0.20)'}`,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          boxShadow: isDark ? '0 0 24px rgba(106,66,255,0.35)' : 'none',
        }}>
          <Icon name="workspace_premium" size={32} color={isDark ? '#8B6FFF' : '#4D21FC'} rounded />
        </div>
        <div style={{
          marginTop: 24,
          fontSize: 11, fontWeight: 600,
          letterSpacing: 2.4, textTransform: 'uppercase',
          color: isDark ? '#8B6FFF' : '#4D21FC',
        }}>Premium</div>
        <h1 style={{
          margin: '12px 0 8px',
          fontSize: 22, fontWeight: 700,
          letterSpacing: '-0.3px', lineHeight: 1.25,
          color: isDark ? '#EDEDED' : '#121316',
        }}>Sync everywhere</h1>
        <p style={{
          margin: 0,
          fontSize: 14, lineHeight: 1.45,
          color: isDark ? '#71747A' : '#8A8D93',
        }}>Google Calendar, iCloud, Outlook, cloud backup, email digests.</p>
        <Tap onClick={onClose} scale={0.97} style={{
          marginTop: 24,
          background: isDark ? '#6A42FF' : '#4D21FC',
          color: 'white',
          borderRadius: 16,
          height: 48,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 15, fontWeight: 600, letterSpacing: 0.1,
        }}>Upgrade to Premium</Tap>
        <Tap onClick={onClose} scale={1} style={{
          marginTop: 4, height: 44,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 14, fontWeight: 500,
          color: isDark ? '#71747A' : '#8A8D93',
        }}>Maybe later</Tap>
      </div>
    </div>
  );
}

Object.assign(window, { QuickAddSheet, PaywallOverlay });
