/* ============================================================
   P2 modals — Schedule, Password Protection, Email Preview,
   Delete Confirm, List-paste Filter.
   All follow the ModalShell pattern from customize_modals.jsx
   (uses the same IconBtn / Btn / Icon primitives from ui.jsx).
   ============================================================ */

/* ---------- Small shared shell (local copy — keeps this file standalone) ---------- */
const P2Shell = ({ open, onClose, title, subtitle, width = 560, children, footer, specId }) => {
  React.useEffect(() => {
    if (!open) return;
    const h = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', h);
    return () => document.removeEventListener('keydown', h);
  }, [open, onClose]);
  if (!open) return null;
  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, zIndex: 220,
      background: 'rgba(15,23,42,0.48)', backdropFilter: 'blur(2px)',
      display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20,
      fontFamily: 'Inter',
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        width, maxWidth: '100%', maxHeight: '90vh',
        background: 'var(--rc-card)', borderRadius: 14,
        border: '1px solid var(--rc-border)',
        boxShadow: '0 30px 60px -15px rgba(15,23,42,0.4)',
        overflow: 'hidden', display: 'flex', flexDirection: 'column',
      }}>
        <div style={{
          padding: '16px 22px', borderBottom: '1px solid var(--rc-border)',
          display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 12,
          flexShrink: 0,
        }}>
          <div style={{ minWidth: 0 }}>
            <div style={{ fontFamily: 'Poppins', fontSize: 17, fontWeight: 700, letterSpacing: '-0.01em', color: 'var(--rc-text)' }}>
              {title}
            </div>
            {subtitle && (
              <div style={{ fontSize: 12, color: 'var(--rc-text-sub)', marginTop: 3 }}>
                {subtitle}
              </div>
            )}
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexShrink: 0 }}>
            <IconBtn name="x" title="Close" onClick={onClose} />
          </div>
        </div>
        <div style={{ flex: 1, overflow: 'auto', padding: 22 }}>
          {children}
        </div>
        {footer && (
          <div style={{
            padding: '14px 22px', borderTop: '1px solid var(--rc-border)',
            background: 'var(--rc-subtle)',
            display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12,
            flexShrink: 0,
          }}>{footer}</div>
        )}
      </div>
    </div>
  );
};

/* ---------- Field wrappers ---------- */
const FieldLabel = ({ children, required, hint }) => (
  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 6 }}>
    <label style={{ fontSize: 12, fontWeight: 600, color: 'var(--rc-text)' }}>
      {children}
      {required && <span style={{ color: 'var(--rc-red, #dc2626)', marginLeft: 3 }}>*</span>}
    </label>
    {hint && <span style={{ fontSize: 11, color: 'var(--rc-text-mute)' }}>{hint}</span>}
  </div>
);

const TextInput = React.forwardRef(({ value, onChange, placeholder, type = 'text', autoFocus, disabled, style }, ref) => (
  <input
    ref={ref}
    type={type}
    value={value ?? ''}
    onChange={e => onChange && onChange(e.target.value)}
    placeholder={placeholder}
    disabled={disabled}
    autoFocus={autoFocus}
    style={{
      width: '100%', padding: '9px 12px', borderRadius: 7,
      border: '1px solid var(--rc-border)', background: disabled ? 'var(--rc-subtle)' : 'var(--rc-card)',
      color: 'var(--rc-text)', fontSize: 13, fontFamily: 'inherit', outline: 'none',
      boxSizing: 'border-box',
      ...style,
    }}
    onFocus={e => e.target.style.borderColor = 'var(--rc-green)'}
    onBlur={e => e.target.style.borderColor = 'var(--rc-border)'}
  />
));

const SegBtn = ({ active, children, onClick, disabled }) => (
  <button onClick={onClick} disabled={disabled} style={{
    flex: 1, padding: '8px 10px',
    border: '1px solid ' + (active ? 'var(--rc-green)' : 'var(--rc-border)'),
    background: active ? 'color-mix(in srgb, var(--rc-green) 12%, var(--rc-card))' : 'var(--rc-card)',
    color: active ? 'var(--rc-green-ink)' : 'var(--rc-text)',
    fontSize: 12, fontWeight: active ? 600 : 500,
    cursor: disabled ? 'not-allowed' : 'pointer', fontFamily: 'inherit',
    opacity: disabled ? 0.5 : 1,
  }}>{children}</button>
);

/* ============================================================
   RC-RPT-040 — Schedule Report modal
   RC-RPT-042 — Email preview (tabbed inside the same modal)
   ============================================================ */
const ScheduleReportModal = ({ open, onClose, reportName = 'Report', onSchedule }) => {
  const [tab, setTab] = React.useState('setup'); // setup | preview
  const [enabled, setEnabled] = React.useState(true);
  const [cadence, setCadence] = React.useState('weekly'); // daily | weekly | monthly
  const [weekday, setWeekday] = React.useState('Mon');
  const [monthday, setMonthday] = React.useState(1);
  const [sendTime, setSendTime] = React.useState('09:00');
  // Auto-detect viewer's IANA timezone for a sensible default
  const userTz = React.useMemo(() => {
    try { return Intl.DateTimeFormat().resolvedOptions().timeZone || 'America/New_York'; }
    catch (e) { return 'America/New_York'; }
  }, []);
  const [timezone, setTimezone] = React.useState(userTz);
  const [format, setFormat] = React.useState('pdf'); // pdf | xlsx | both
  const [recipients, setRecipients] = React.useState('');
  const [subject, setSubject] = React.useState(`${reportName} — weekly digest`);
  const [note, setNote] = React.useState('');
  const [testSending, setTestSending] = React.useState(false);

  React.useEffect(() => { if (open) { setTab('setup'); setSubject(`${reportName} — ${cadence} digest`); } }, [open]);
  React.useEffect(() => { setSubject(`${reportName} — ${cadence} digest`); }, [cadence, reportName]);

  if (!open) return null;
  const recipientList = recipients.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  const canSave = enabled ? recipientList.length > 0 : true;

  const scheduleSummary = () => {
    if (!enabled) return 'Paused';
    const t = sendTime;
    if (cadence === 'daily') return `Every day at ${t}`;
    if (cadence === 'weekly') return `Every ${weekday} at ${t}`;
    return `Day ${monthday} of each month at ${t}`;
  };

  // Next-delivery calc (shows a concrete datetime in recipient's eyes, not just a pattern).
  // Rough client-side — doesn't solve DST transitions precisely, fine for the prototype.
  const nextDelivery = React.useMemo(() => {
    try {
      const now = new Date();
      const [hh, mm] = sendTime.split(':').map(Number);
      let d = new Date(now);
      d.setHours(hh, mm, 0, 0);
      if (cadence === 'daily') {
        if (d <= now) d.setDate(d.getDate() + 1);
      } else if (cadence === 'weekly') {
        const targetDow = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'].indexOf(weekday) || 0;
        const diff = (targetDow - d.getDay() + 7) % 7;
        d.setDate(d.getDate() + diff);
        if (d <= now) d.setDate(d.getDate() + 7);
      } else {
        d.setDate(monthday === -1 ? 28 : monthday);
        if (d <= now) d.setMonth(d.getMonth() + 1);
      }
      return d.toLocaleDateString('en-US', {
        weekday: 'short', month: 'short', day: 'numeric',
        hour: 'numeric', minute: '2-digit', timeZone: timezone, timeZoneName: 'short',
      });
    } catch (e) { return null; }
  }, [cadence, weekday, monthday, sendTime, timezone]);

  // Test-send — simulate a network call, then toast. Requires at least one recipient.
  const doTestSend = () => {
    if (testSending) return;
    if (recipientList.length === 0) {
      window.__rcToast && window.__rcToast.push && window.__rcToast.push({
        kind: 'warn',
        title: 'Add a recipient first',
        detail: 'Test emails need at least one valid address.',
        timeout: 3000,
      });
      return;
    }
    setTestSending(true);
    window.__rcToast && window.__rcToast.push && window.__rcToast.push({
      kind: 'info',
      title: 'Sending test…',
      detail: `Preview email to ${recipientList[0]}${recipientList.length > 1 ? ` +${recipientList.length - 1}` : ''}`,
      timeout: 1800,
    });
    setTimeout(() => {
      setTestSending(false);
      window.__rcToast && window.__rcToast.push && window.__rcToast.push({
        kind: 'success',
        title: 'Test sent',
        detail: `Delivered to ${recipientList.length} recipient${recipientList.length === 1 ? '' : 's'}. Check your inbox.`,
        timeout: 4000,
      });
    }, 1700);
  };

  return (
    <P2Shell
      open={open} onClose={onClose}
      title="Schedule Report"
      subtitle={`Deliver ${reportName} on a recurring schedule — PDF + XLSX attachments, email-delivered.`}
      specId="RC-RPT-040"
      width={680}
      footer={
        <>
          <div style={{ fontSize: 11, color: 'var(--rc-text-sub)', display: 'flex', flexDirection: 'column', gap: 2 }}>
            <div>
              <Icon name="clock" size={11} /> &nbsp;{scheduleSummary()} · {recipientList.length} recipient{recipientList.length === 1 ? '' : 's'}
            </div>
            {enabled && nextDelivery && (
              <div style={{ color: 'var(--rc-text-mute)', fontFamily: 'JetBrains Mono, monospace', fontSize: 10 }}>
                Next: {nextDelivery}
              </div>
            )}
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <button
              onClick={doTestSend}
              disabled={testSending}
              title="Send a one-off preview email to the recipient list right now"
              style={{
                padding: '7px 12px', borderRadius: 7, border: '1px solid var(--rc-border)',
                background: 'var(--rc-card)', color: 'var(--rc-text)', fontSize: 12,
                fontWeight: 500, cursor: testSending ? 'wait' : 'pointer',
                fontFamily: 'inherit',
                display: 'inline-flex', alignItems: 'center', gap: 5,
                opacity: testSending ? 0.6 : 1,
              }}
              onMouseEnter={e => { if (!testSending) e.currentTarget.style.background = 'var(--rc-hover)'; }}
              onMouseLeave={e => { e.currentTarget.style.background = 'var(--rc-card)'; }}>
              <Icon name={testSending ? 'refresh' : 'mail'} size={11} />
              {testSending ? 'Sending…' : 'Test send now'}
            </button>
            <button onClick={onClose} style={{
              padding: '7px 14px', borderRadius: 7, border: '1px solid var(--rc-border)',
              background: 'var(--rc-card)', color: 'var(--rc-text)', fontSize: 12,
              fontWeight: 500, cursor: 'pointer', fontFamily: 'inherit',
            }}>Cancel</button>
            <button
              disabled={!canSave}
              onClick={() => {
                const payload = { enabled, cadence, weekday, monthday, sendTime, timezone, format, recipients: recipientList, subject, note };
                onSchedule && onSchedule(payload);
                window.__rcToast && window.__rcToast.push
                  ? window.__rcToast.push({ tone: 'success', title: 'Scheduled', detail: scheduleSummary() })
                  : null;
                onClose();
              }}
              style={{
                padding: '7px 16px', borderRadius: 7, border: 0,
                background: canSave ? 'var(--rc-green)' : 'color-mix(in srgb, var(--rc-green) 45%, transparent)',
                color: '#fff', fontSize: 12, fontWeight: 600,
                cursor: canSave ? 'pointer' : 'not-allowed', fontFamily: 'inherit',
              }}>Save schedule</button>
          </div>
        </>
      }>
      {/* Tabs */}
      <div style={{ display: 'flex', borderBottom: '1px solid var(--rc-border)', marginBottom: 18, marginTop: -4 }}>
        {[
          { id: 'setup',   label: 'Setup',        icon: 'settings' },
          { id: 'preview', label: 'Email preview', icon: 'mail', specId: 'RC-RPT-042' },
        ].map(t => (
          <button key={t.id} onClick={() => setTab(t.id)} style={{
            padding: '7px 14px',
            border: 0, background: 'transparent', cursor: 'pointer', fontFamily: 'inherit',
            fontSize: 12, fontWeight: tab === t.id ? 600 : 500,
            color: tab === t.id ? 'var(--rc-text)' : 'var(--rc-text-sub)',
            borderBottom: '2px solid ' + (tab === t.id ? 'var(--rc-green)' : 'transparent'),
            marginBottom: -1,
            display: 'inline-flex', alignItems: 'center', gap: 6,
          }}>
            <Icon name={t.icon} size={12} />
            {t.label}
          </button>
        ))}
      </div>

      {tab === 'setup' ? (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          {/* Enable toggle */}
          <label style={{
            display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer',
            padding: '10px 12px', borderRadius: 8,
            background: enabled ? 'color-mix(in srgb, var(--rc-green) 8%, transparent)' : 'var(--rc-subtle)',
            border: '1px solid ' + (enabled ? 'color-mix(in srgb, var(--rc-green) 30%, transparent)' : 'var(--rc-border)'),
          }}>
            <span style={{
              width: 32, height: 18, borderRadius: 9999, position: 'relative', flexShrink: 0,
              background: enabled ? 'var(--rc-green)' : 'var(--rc-border)',
              transition: 'background 120ms',
            }}>
              <span style={{
                position: 'absolute', top: 2, left: enabled ? 16 : 2,
                width: 14, height: 14, borderRadius: 9999, background: '#fff',
                boxShadow: '0 1px 2px rgba(0,0,0,0.2)', transition: 'left 120ms',
              }} />
            </span>
            <input type="checkbox" checked={enabled} onChange={e => setEnabled(e.target.checked)} style={{ display: 'none' }} />
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--rc-text)' }}>
                {enabled ? 'Schedule active' : 'Schedule paused'}
              </div>
              <div style={{ fontSize: 11, color: 'var(--rc-text-sub)' }}>
                {enabled ? 'Emails will be sent on the schedule below' : 'No emails will be sent until resumed'}
              </div>
            </div>
          </label>

          {/* Cadence */}
          <div>
            <FieldLabel required>Cadence</FieldLabel>
            <div style={{ display: 'flex', gap: 6 }}>
              <SegBtn active={cadence === 'daily'} onClick={() => setCadence('daily')}>Daily</SegBtn>
              <SegBtn active={cadence === 'weekly'} onClick={() => setCadence('weekly')}>Weekly</SegBtn>
              <SegBtn active={cadence === 'monthly'} onClick={() => setCadence('monthly')}>Monthly</SegBtn>
            </div>
          </div>

          {/* Specifics by cadence */}
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 10 }}>
            {cadence === 'weekly' && (
              <div style={{ gridColumn: 'span 2' }}>
                <FieldLabel>Day of week</FieldLabel>
                <div style={{ display: 'flex', gap: 4 }}>
                  {['Mon','Tue','Wed','Thu','Fri','Sat','Sun'].map(d => (
                    <button key={d} onClick={() => setWeekday(d)} style={{
                      flex: 1, padding: '7px 0', borderRadius: 6,
                      border: '1px solid ' + (weekday === d ? 'var(--rc-green)' : 'var(--rc-border)'),
                      background: weekday === d ? 'var(--rc-green)' : 'var(--rc-card)',
                      color: weekday === d ? '#fff' : 'var(--rc-text)',
                      fontSize: 11, fontWeight: weekday === d ? 600 : 500,
                      cursor: 'pointer', fontFamily: 'inherit',
                    }}>{d}</button>
                  ))}
                </div>
              </div>
            )}
            {cadence === 'monthly' && (
              <div style={{ gridColumn: 'span 2' }}>
                <FieldLabel>Day of month</FieldLabel>
                <select value={monthday} onChange={e => setMonthday(Number(e.target.value))} style={{
                  width: '100%', padding: '9px 12px', borderRadius: 7,
                  border: '1px solid var(--rc-border)', background: 'var(--rc-card)',
                  color: 'var(--rc-text)', fontSize: 13, fontFamily: 'inherit',
                }}>
                  {Array.from({ length: 28 }, (_, i) => i + 1).map(d => (
                    <option key={d} value={d}>{d}{d === 1 ? 'st' : d === 2 ? 'nd' : d === 3 ? 'rd' : 'th'} of month</option>
                  ))}
                  <option value={-1}>Last day of month</option>
                </select>
              </div>
            )}
            <div style={{ gridColumn: cadence === 'daily' ? 'span 2' : 'span 1' }}>
              <FieldLabel>Send at</FieldLabel>
              <select value={sendTime} onChange={e => setSendTime(e.target.value)} style={{
                width: '100%', padding: '9px 12px', borderRadius: 7,
                border: '1px solid var(--rc-border)', background: 'var(--rc-card)',
                color: 'var(--rc-text)', fontSize: 13, fontFamily: 'inherit',
              }}>
                {Array.from({ length: 24 }, (_, i) => `${String(i).padStart(2,'0')}:00`).map(t => (
                  <option key={t} value={t}>{t}</option>
                ))}
              </select>
            </div>
            <div style={{ gridColumn: cadence === 'daily' ? 'span 1' : 'span 3' }}>
              <FieldLabel>Timezone</FieldLabel>
              <select value={timezone} onChange={e => setTimezone(e.target.value)} style={{
                width: '100%', padding: '9px 12px', borderRadius: 7,
                border: '1px solid var(--rc-border)', background: 'var(--rc-card)',
                color: 'var(--rc-text)', fontSize: 13, fontFamily: 'inherit',
              }}>
                {/* If user's detected zone isn't in the canned list, prepend it so it's always selectable */}
                {!['America/New_York','America/Chicago','America/Denver','America/Los_Angeles','UTC','Europe/London','Europe/Paris'].includes(userTz) && (
                  <option value={userTz}>{userTz} (your zone)</option>
                )}
                <option value="America/New_York">America/New York (Eastern)</option>
                <option value="America/Chicago">America/Chicago (Central)</option>
                <option value="America/Denver">America/Denver (Mountain)</option>
                <option value="America/Los_Angeles">America/Los Angeles (Pacific)</option>
                <option value="UTC">UTC</option>
                <option value="Europe/London">Europe/London</option>
                <option value="Europe/Paris">Europe/Paris</option>
              </select>
              {timezone !== userTz && (
                <div style={{ fontSize: 10, color: 'var(--rc-text-mute)', marginTop: 4,
                  display: 'flex', alignItems: 'center', gap: 4 }}>
                  <Icon name="info" size={10} />
                  Your browser is on <b style={{ color: 'var(--rc-text-sub)', fontWeight: 500 }}>{userTz}</b> —
                  <button onClick={() => setTimezone(userTz)} style={{
                    border: 0, background: 'transparent', padding: 0, cursor: 'pointer',
                    color: 'var(--rc-green)', fontSize: 10, fontWeight: 500, fontFamily: 'inherit',
                    textDecoration: 'underline',
                  }}>use mine</button>
                </div>
              )}
            </div>
          </div>

          {/* Format */}
          <div>
            <FieldLabel>Attachments</FieldLabel>
            <div style={{ display: 'flex', gap: 6 }}>
              <SegBtn active={format === 'pdf'}  onClick={() => setFormat('pdf')}>PDF</SegBtn>
              <SegBtn active={format === 'xlsx'} onClick={() => setFormat('xlsx')}>XLSX data</SegBtn>
              <SegBtn active={format === 'both'} onClick={() => setFormat('both')}>Both</SegBtn>
            </div>
          </div>

          {/* Recipients */}
          <div>
            <FieldLabel required hint="Comma-separated">Recipients</FieldLabel>
            <textarea
              value={recipients}
              onChange={e => setRecipients(e.target.value)}
              placeholder="alice@brand.com, bob@brand.com"
              rows={2}
              style={{
                width: '100%', padding: '9px 12px', borderRadius: 7,
                border: '1px solid var(--rc-border)', background: 'var(--rc-card)',
                color: 'var(--rc-text)', fontSize: 13, fontFamily: 'inherit', outline: 'none',
                resize: 'vertical', boxSizing: 'border-box',
              }}
              onFocus={e => e.target.style.borderColor = 'var(--rc-green)'}
              onBlur={e => e.target.style.borderColor = 'var(--rc-border)'}
            />
            {recipientList.length > 0 && (
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4, marginTop: 8 }}>
                {recipientList.map((r, i) => (
                  <span key={i} style={{
                    padding: '2px 8px', borderRadius: 9999, fontSize: 11,
                    background: 'var(--rc-chip-bg)', color: 'var(--rc-text)',
                    border: '1px solid var(--rc-border)',
                  }}>{r}</span>
                ))}
              </div>
            )}
          </div>

          {/* Subject + note */}
          <div>
            <FieldLabel>Email subject</FieldLabel>
            <TextInput value={subject} onChange={setSubject} />
          </div>
          <div>
            <FieldLabel hint="Optional — appears above the report">Note</FieldLabel>
            <textarea
              value={note}
              onChange={e => setNote(e.target.value)}
              placeholder="Context for recipients..."
              rows={2}
              style={{
                width: '100%', padding: '9px 12px', borderRadius: 7,
                border: '1px solid var(--rc-border)', background: 'var(--rc-card)',
                color: 'var(--rc-text)', fontSize: 13, fontFamily: 'inherit', outline: 'none',
                resize: 'vertical', boxSizing: 'border-box',
              }}
            />
          </div>
        </div>
      ) : (
        /* RC-RPT-042 — Email preview */
        <ScheduledEmailPreview
          reportName={reportName}
          cadence={cadence}
          subject={subject}
          note={note}
          format={format}
          recipients={recipientList}
          scheduleSummary={scheduleSummary()}
        />
      )}
    </P2Shell>
  );
};

/* ---------- Inline email preview (RC-RPT-042) ---------- */
const ScheduledEmailPreview = ({ reportName, cadence, subject, note, format, recipients, scheduleSummary }) => {
  const today = new Date();
  const fmtDate = today.toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' });
  return (
    <div>
      <div style={{
        fontSize: 11, color: 'var(--rc-text-sub)', marginBottom: 12,
        display: 'flex', alignItems: 'center', gap: 8,
        padding: '8px 10px', borderRadius: 6,
        background: 'var(--rc-subtle)', border: '1px solid var(--rc-border)',
      }}>
        <Icon name="info" size={12} color="var(--rc-text-sub)" />
        Recipients see this email on each delivery.
      </div>

      <div style={{
        border: '1px solid var(--rc-border)', borderRadius: 10,
        background: '#ffffff', overflow: 'hidden',
      }}>
        {/* Email header */}
        <div style={{ padding: '12px 14px', borderBottom: '1px solid #e5e7eb', fontSize: 11, color: '#6b7280' }}>
          <div style={{ display: 'flex', gap: 6 }}><b style={{ width: 50, color: '#374151' }}>From</b> reports@mixshift.io</div>
          <div style={{ display: 'flex', gap: 6 }}><b style={{ width: 50, color: '#374151' }}>To</b> {recipients.length ? recipients.join(', ') : 'you@brand.com'}</div>
          <div style={{ display: 'flex', gap: 6 }}><b style={{ width: 50, color: '#374151' }}>Subject</b> <span style={{ color: '#111827' }}>{subject || `${reportName} — ${cadence} digest`}</span></div>
          <div style={{ display: 'flex', gap: 6 }}><b style={{ width: 50, color: '#374151' }}>Date</b> {fmtDate}</div>
        </div>

        {/* Email body */}
        <div style={{ padding: '20px 22px', fontSize: 13, color: '#111827', lineHeight: 1.55 }}>
          <div style={{
            display: 'flex', alignItems: 'center', gap: 10, marginBottom: 18,
            paddingBottom: 14, borderBottom: '1px solid #e5e7eb',
          }}>
            <div style={{
              width: 32, height: 32, borderRadius: 8,
              background: '#16a34a', color: '#fff',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontWeight: 700, fontSize: 14, fontFamily: 'Poppins',
            }}>MS</div>
            <div>
              <div style={{ fontWeight: 700, fontSize: 14, fontFamily: 'Poppins' }}>MixShift Reports</div>
              <div style={{ fontSize: 11, color: '#6b7280' }}>{scheduleSummary}</div>
            </div>
          </div>

          <p style={{ margin: '0 0 14px' }}>Hi team,</p>
          <p style={{ margin: '0 0 14px' }}>
            Your {cadence} report for <b>{reportName}</b> is ready. The full PDF and data file are
            attached, and the summary below covers the period ending {fmtDate}.
          </p>

          {note && (
            <div style={{
              margin: '0 0 16px', padding: '10px 12px',
              background: '#f9fafb', borderLeft: '3px solid #16a34a',
              borderRadius: 4, fontSize: 12, color: '#374151',
            }}>{note}</div>
          )}

          {/* Mock scorecard strip */}
          <div style={{
            display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8,
            margin: '0 0 18px',
          }}>
            {[
              { label: 'Revenue', value: '$128.4K', delta: '+7.2%', up: true },
              { label: 'Units',   value: '4,412',   delta: '+3.1%', up: true },
              { label: 'ACOS',    value: '18.4%',   delta: '-1.3pt', up: true },
            ].map(s => (
              <div key={s.label} style={{
                padding: '10px 12px', border: '1px solid #e5e7eb', borderRadius: 6,
                background: '#f9fafb',
              }}>
                <div style={{ fontSize: 10, color: '#6b7280', textTransform: 'uppercase', letterSpacing: '0.04em' }}>{s.label}</div>
                <div style={{ fontSize: 16, fontWeight: 700, color: '#111827', marginTop: 2, fontFamily: 'Poppins' }}>{s.value}</div>
                <div style={{ fontSize: 11, color: s.up ? '#16a34a' : '#dc2626', fontWeight: 500 }}>{s.delta} vs prior period</div>
              </div>
            ))}
          </div>

          {/* Attachment pills */}
          <div style={{ margin: '16px 0 6px', fontSize: 11, fontWeight: 600, color: '#374151' }}>
            Attachments
          </div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
            {(format === 'pdf' || format === 'both') && (
              <span style={{
                display: 'inline-flex', alignItems: 'center', gap: 6,
                padding: '5px 10px', borderRadius: 6, fontSize: 11,
                background: '#fef2f2', color: '#991b1b', border: '1px solid #fecaca',
              }}>
                <Icon name="file" size={11} /> {reportName}.pdf
              </span>
            )}
            {(format === 'xlsx' || format === 'both') && (
              <span style={{
                display: 'inline-flex', alignItems: 'center', gap: 6,
                padding: '5px 10px', borderRadius: 6, fontSize: 11,
                background: '#f0fdf4', color: '#166534', border: '1px solid #bbf7d0',
              }}>
                <Icon name="file" size={11} /> {reportName}.xlsx
              </span>
            )}
          </div>

          {/* CTA */}
          <div style={{ margin: '20px 0 6px' }}>
            <span style={{
              display: 'inline-block', padding: '9px 18px', borderRadius: 6,
              background: '#16a34a', color: '#fff', fontSize: 13, fontWeight: 600,
            }}>Open live report →</span>
          </div>

          <div style={{
            marginTop: 22, paddingTop: 14, borderTop: '1px solid #e5e7eb',
            fontSize: 11, color: '#6b7280',
          }}>
            Sent by MixShift · <a style={{ color: '#16a34a' }}>Manage delivery</a> · <a style={{ color: '#16a34a' }}>Unsubscribe</a>
          </div>
        </div>
      </div>
    </div>
  );
};

/* ============================================================
   RC-RPT-022 — Password Protection modal (opens from Share)
   ============================================================ */
const PasswordProtectionModal = ({ open, onClose, hasPassword, onSet, onRemove }) => {
  const [pwd, setPwd] = React.useState('');
  const [confirm, setConfirm] = React.useState('');
  const [show, setShow] = React.useState(false);
  React.useEffect(() => { if (open) { setPwd(''); setConfirm(''); setShow(false); } }, [open]);
  if (!open) return null;
  const strong = pwd.length >= 8;
  const match = pwd && pwd === confirm;
  const canSave = strong && match;
  return (
    <P2Shell
      open={open} onClose={onClose}
      title={hasPassword ? 'Update password' : 'Set a password'}
      subtitle="Require viewers to enter this password before the shared link loads."
      specId="RC-RPT-022"
      width={480}
      footer={
        <>
          {hasPassword ? (
            <button onClick={() => { onRemove && onRemove(); onClose(); }} style={{
              padding: '7px 14px', borderRadius: 7,
              border: '1px solid color-mix(in srgb, var(--rc-red, #dc2626) 35%, transparent)',
              background: 'var(--rc-card)', color: 'var(--rc-red, #dc2626)',
              fontSize: 12, fontWeight: 500, cursor: 'pointer', fontFamily: 'inherit',
            }}>Remove password</button>
          ) : <span />}
          <div style={{ display: 'flex', gap: 8 }}>
            <button onClick={onClose} style={{
              padding: '7px 14px', borderRadius: 7, border: '1px solid var(--rc-border)',
              background: 'var(--rc-card)', color: 'var(--rc-text)', fontSize: 12,
              fontWeight: 500, cursor: 'pointer', fontFamily: 'inherit',
            }}>Cancel</button>
            <button
              disabled={!canSave}
              onClick={() => { onSet && onSet(pwd); onClose(); }}
              style={{
                padding: '7px 16px', borderRadius: 7, border: 0,
                background: canSave ? 'var(--rc-green)' : 'color-mix(in srgb, var(--rc-green) 45%, transparent)',
                color: '#fff', fontSize: 12, fontWeight: 600,
                cursor: canSave ? 'pointer' : 'not-allowed', fontFamily: 'inherit',
              }}>{hasPassword ? 'Update' : 'Set password'}</button>
          </div>
        </>
      }>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        <div style={{
          padding: '10px 12px', borderRadius: 7,
          background: 'color-mix(in srgb, var(--rc-amber, #f59e0b) 8%, var(--rc-card))',
          border: '1px solid color-mix(in srgb, var(--rc-amber, #f59e0b) 35%, var(--rc-border))',
          fontSize: 12, color: 'var(--rc-text)',
          display: 'flex', gap: 8, alignItems: 'flex-start',
        }}>
          <Icon name="lock" size={13} color="var(--rc-text-sub)" />
          <div>
            Password is applied to <b>every share link</b> for this report. Existing viewers will be prompted
            on their next visit.
          </div>
        </div>

        <div>
          <FieldLabel required>New password</FieldLabel>
          <div style={{ position: 'relative' }}>
            <TextInput
              type={show ? 'text' : 'password'}
              value={pwd}
              onChange={setPwd}
              placeholder="At least 8 characters"
              autoFocus
              style={{ paddingRight: 68 }}
            />
            <button onClick={() => setShow(!show)} style={{
              position: 'absolute', right: 6, top: '50%', transform: 'translateY(-50%)',
              padding: '4px 9px', border: 0, borderRadius: 5,
              background: 'transparent', color: 'var(--rc-text-sub)',
              fontSize: 11, cursor: 'pointer', fontFamily: 'inherit', fontWeight: 500,
            }}>{show ? 'Hide' : 'Show'}</button>
          </div>
          <div style={{ marginTop: 6, fontSize: 11, color: strong ? 'var(--rc-green-ink)' : 'var(--rc-text-mute)' }}>
            {strong ? '✓ Password length looks good' : 'Must be at least 8 characters'}
          </div>
        </div>

        <div>
          <FieldLabel required>Confirm password</FieldLabel>
          <TextInput
            type={show ? 'text' : 'password'}
            value={confirm}
            onChange={setConfirm}
            placeholder="Re-enter password"
          />
          {confirm && !match && (
            <div style={{ marginTop: 6, fontSize: 11, color: 'var(--rc-red, #dc2626)' }}>
              Passwords don't match
            </div>
          )}
        </div>
      </div>
    </P2Shell>
  );
};

/* ============================================================
   RC-RPT-013 — Delete report confirmation
   Includes core-instance-suppression warning + 403 fallback.
   ============================================================ */
const DeleteReportConfirmModal = ({ open, onClose, reportName, isCore, onConfirm }) => {
  const [typed, setTyped] = React.useState('');
  React.useEffect(() => { if (open) setTyped(''); }, [open]);
  if (!open) return null;

  const matches = typed.trim().toLowerCase() === (reportName || '').toLowerCase();

  if (isCore) {
    // Suppression path — UI surface for the 403 response.
    return (
      <P2Shell
        open={open} onClose={onClose}
        title="This report can't be deleted"
        subtitle="Core report instances are seeded per brand × platform × marketplace and cannot be removed."
        specId="RC-RPT-013"
        width={480}
        footer={
          <>
            <span />
            <button onClick={onClose} style={{
              padding: '7px 16px', borderRadius: 7, border: 0,
              background: 'var(--rc-green)', color: '#fff',
              fontSize: 12, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit',
            }}>Got it</button>
          </>
        }>
        <div style={{
          padding: '14px 16px', borderRadius: 8,
          background: 'color-mix(in srgb, var(--rc-amber, #f59e0b) 8%, var(--rc-card))',
          border: '1px solid color-mix(in srgb, var(--rc-amber, #f59e0b) 35%, var(--rc-border))',
          fontSize: 13, color: 'var(--rc-text)',
        }}>
          <div style={{ display: 'flex', gap: 10, alignItems: 'flex-start' }}>
            <Icon name="info" size={14} color="var(--rc-text-sub)" />
            <div>
              <b>"{reportName}"</b> is one of the default reports seeded for this marketplace.
              You can archive or hide it, but deleting it would leave the Reports list in an
              inconsistent state. Duplicates you created are removable.
            </div>
          </div>
        </div>
      </P2Shell>
    );
  }

  return (
    <P2Shell
      open={open} onClose={onClose}
      title="Delete report?"
      subtitle="This action is permanent. Scheduled deliveries and share links will stop working."
      specId="RC-RPT-013"
      width={480}
      footer={
        <>
          <span />
          <div style={{ display: 'flex', gap: 8 }}>
            <button onClick={onClose} style={{
              padding: '7px 14px', borderRadius: 7, border: '1px solid var(--rc-border)',
              background: 'var(--rc-card)', color: 'var(--rc-text)', fontSize: 12,
              fontWeight: 500, cursor: 'pointer', fontFamily: 'inherit',
            }}>Cancel</button>
            <button
              disabled={!matches}
              onClick={() => { onConfirm && onConfirm(); onClose(); }}
              style={{
                padding: '7px 16px', borderRadius: 7, border: 0,
                background: matches ? 'var(--rc-red, #dc2626)' : 'color-mix(in srgb, var(--rc-red, #dc2626) 45%, transparent)',
                color: '#fff', fontSize: 12, fontWeight: 600,
                cursor: matches ? 'pointer' : 'not-allowed', fontFamily: 'inherit',
              }}>Delete report</button>
          </div>
        </>
      }>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        <div style={{
          padding: '12px 14px', borderRadius: 8,
          background: 'color-mix(in srgb, var(--rc-red, #dc2626) 6%, var(--rc-card))',
          border: '1px solid color-mix(in srgb, var(--rc-red, #dc2626) 30%, var(--rc-border))',
          fontSize: 12, color: 'var(--rc-text)',
        }}>
          <div style={{ display: 'flex', gap: 8, alignItems: 'flex-start' }}>
            <Icon name="x" size={14} color="var(--rc-red, #dc2626)" />
            <div>
              Deleting <b>"{reportName}"</b> will also remove:
              <ul style={{ margin: '6px 0 0', paddingLeft: 18, color: 'var(--rc-text-sub)' }}>
                <li>All share links and passwords</li>
                <li>Scheduled email deliveries</li>
                <li>Saved named views and per-user defaults</li>
              </ul>
            </div>
          </div>
        </div>
        <div>
          <FieldLabel required hint="Case-insensitive">
            Type the report name to confirm
          </FieldLabel>
          <TextInput
            value={typed} onChange={setTyped}
            placeholder={reportName}
            autoFocus
          />
        </div>
      </div>
    </P2Shell>
  );
};

/* ============================================================
   RC-PAGE-024 — List-paste filter input (bulk value entry).
   Used by filter dropdowns on the 4 report pages (ASIN, SKU, keyword, etc).
   ============================================================ */
const ListPasteFilterModal = ({ open, onClose, dimensionLabel = 'ASIN', onApply }) => {
  const [raw, setRaw] = React.useState('');
  const [mode, setMode] = React.useState('include'); // include | exclude
  React.useEffect(() => { if (open) { setRaw(''); setMode('include'); } }, [open]);
  if (!open) return null;

  const values = raw.split(/[\s,;\n\r\t]+/).map(s => s.trim()).filter(Boolean);
  const unique = [...new Set(values)];
  const dupCount = values.length - unique.length;

  // Fake validation — real validateValues(dimension, values[]) happens server-side per spec.
  const ASIN_RE = /^[A-Z0-9]{10}$/;
  const looksLikeAsin = dimensionLabel.toLowerCase().includes('asin');
  const valid = looksLikeAsin ? unique.filter(v => ASIN_RE.test(v)) : unique;
  const invalid = looksLikeAsin ? unique.filter(v => !ASIN_RE.test(v)) : [];

  return (
    <P2Shell
      open={open} onClose={onClose}
      title={`Paste ${dimensionLabel} list`}
      subtitle="One value per line, or separated by commas / tabs / spaces."
      specId="RC-PAGE-024"
      width={560}
      footer={
        <>
          <div style={{ fontSize: 11, color: 'var(--rc-text-sub)', fontFamily: 'JetBrains Mono, monospace' }}>
            <b style={{ color: 'var(--rc-green-ink)' }}>{valid.length}</b> valid
            {invalid.length > 0 && <> · <b style={{ color: 'var(--rc-red, #dc2626)' }}>{invalid.length}</b> invalid</>}
            {dupCount > 0 && <> · <b>{dupCount}</b> duplicate{dupCount === 1 ? '' : 's'} removed</>}
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <button onClick={onClose} style={{
              padding: '7px 14px', borderRadius: 7, border: '1px solid var(--rc-border)',
              background: 'var(--rc-card)', color: 'var(--rc-text)', fontSize: 12,
              fontWeight: 500, cursor: 'pointer', fontFamily: 'inherit',
            }}>Cancel</button>
            <button
              disabled={valid.length === 0}
              onClick={() => { onApply && onApply({ values: valid, mode }); onClose(); }}
              style={{
                padding: '7px 16px', borderRadius: 7, border: 0,
                background: valid.length ? 'var(--rc-green)' : 'color-mix(in srgb, var(--rc-green) 45%, transparent)',
                color: '#fff', fontSize: 12, fontWeight: 600,
                cursor: valid.length ? 'pointer' : 'not-allowed', fontFamily: 'inherit',
              }}>Apply filter</button>
          </div>
        </>
      }>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        <div>
          <FieldLabel>Mode</FieldLabel>
          <div style={{ display: 'flex', gap: 6 }}>
            <SegBtn active={mode === 'include'} onClick={() => setMode('include')}>Include these {dimensionLabel}s</SegBtn>
            <SegBtn active={mode === 'exclude'} onClick={() => setMode('exclude')}>Exclude these {dimensionLabel}s</SegBtn>
          </div>
        </div>

        <div>
          <FieldLabel required hint={`Up to 5,000 ${dimensionLabel}s`}>Paste values</FieldLabel>
          <textarea
            value={raw}
            onChange={e => setRaw(e.target.value)}
            placeholder={looksLikeAsin
              ? 'B07XYZ1234\nB08ABCD234\nB09EFGH567\n...'
              : 'value-1\nvalue-2\nvalue-3\n...'}
            rows={8}
            style={{
              width: '100%', padding: '10px 12px', borderRadius: 7,
              border: '1px solid var(--rc-border)', background: 'var(--rc-card)',
              color: 'var(--rc-text)', fontSize: 12,
              fontFamily: 'JetBrains Mono, monospace',
              outline: 'none', resize: 'vertical', boxSizing: 'border-box',
            }}
            autoFocus
            onFocus={e => e.target.style.borderColor = 'var(--rc-green)'}
            onBlur={e => e.target.style.borderColor = 'var(--rc-border)'}
          />
        </div>

        {invalid.length > 0 && (
          <div style={{
            padding: '10px 12px', borderRadius: 7,
            background: 'color-mix(in srgb, var(--rc-red, #dc2626) 5%, var(--rc-card))',
            border: '1px solid color-mix(in srgb, var(--rc-red, #dc2626) 30%, var(--rc-border))',
            fontSize: 11, color: 'var(--rc-text)',
          }}>
            <div style={{ fontWeight: 600, marginBottom: 6, color: 'var(--rc-red, #dc2626)' }}>
              {invalid.length} value{invalid.length === 1 ? '' : 's'} won't match the {dimensionLabel} format:
            </div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4, maxHeight: 80, overflowY: 'auto' }}>
              {invalid.slice(0, 40).map((v, i) => (
                <span key={i} style={{
                  padding: '1px 7px', borderRadius: 4, fontSize: 10,
                  background: 'color-mix(in srgb, var(--rc-red, #dc2626) 10%, transparent)',
                  color: 'var(--rc-red, #dc2626)', fontFamily: 'JetBrains Mono, monospace',
                }}>{v}</span>
              ))}
              {invalid.length > 40 && (
                <span style={{ fontSize: 10, color: 'var(--rc-text-mute)' }}>+{invalid.length - 40} more</span>
              )}
            </div>
          </div>
        )}

        {valid.length > 0 && (
          <div style={{
            padding: '10px 12px', borderRadius: 7,
            background: 'var(--rc-subtle)', border: '1px solid var(--rc-border)',
            fontSize: 11, color: 'var(--rc-text)',
          }}>
            <div style={{ fontWeight: 600, marginBottom: 6 }}>
              Preview — {valid.length} {dimensionLabel}{valid.length === 1 ? '' : 's'} will be {mode === 'include' ? 'included' : 'excluded'}
            </div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4, maxHeight: 80, overflowY: 'auto' }}>
              {valid.slice(0, 20).map((v, i) => (
                <span key={i} style={{
                  padding: '1px 7px', borderRadius: 4, fontSize: 10,
                  background: 'var(--rc-card)', color: 'var(--rc-text)',
                  border: '1px solid var(--rc-border)',
                  fontFamily: 'JetBrains Mono, monospace',
                }}>{v}</span>
              ))}
              {valid.length > 20 && (
                <span style={{ fontSize: 10, color: 'var(--rc-text-mute)' }}>+{valid.length - 20} more</span>
              )}
            </div>
          </div>
        )}
      </div>
    </P2Shell>
  );
};

/* ============================================================
   RC-PAGE-041 — Save current page state as new default
   Editor-only, shows a diff + confirmation checkbox before writing.
   ============================================================ */
const SaveAsDefaultConfirmModal = ({ open, onClose, currentState, existingDefault, onConfirm }) => {
  const [ack, setAck] = React.useState(false);
  React.useEffect(() => { if (open) setAck(false); }, [open]);
  if (!open) return null;

  // Compute diff between current and stored default (if any).
  const currentKeys = currentState ? Object.keys(currentState) : [];
  const diff = [];
  currentKeys.forEach(k => {
    const cur = currentState[k];
    const prev = existingDefault ? existingDefault[k] : undefined;
    const curS = JSON.stringify(cur);
    const prevS = JSON.stringify(prev);
    if (curS !== prevS) diff.push({ key: k, from: prev, to: cur });
  });

  const hasPrior = existingDefault != null;
  const nothingChanged = hasPrior && diff.length === 0;

  return (
    <P2Shell
      open={open} onClose={onClose}
      title={hasPrior ? 'Update page defaults?' : 'Save current page state as your default?'}
      subtitle="Applies to this report, scoped to your account. Teammates aren't affected."
      specId="RC-PAGE-041"
      width={520}
      footer={
        <>
          <span style={{ fontSize: 10, color: 'var(--rc-text-mute)' }}>
            You can revert anytime via "Reset to defaults".
          </span>
          <div style={{ display: 'flex', gap: 8 }}>
            <button onClick={onClose} style={{
              padding: '7px 14px', borderRadius: 7, border: '1px solid var(--rc-border)',
              background: 'var(--rc-card)', color: 'var(--rc-text)', fontSize: 12,
              fontWeight: 500, cursor: 'pointer', fontFamily: 'inherit',
            }}>Cancel</button>
            <button
              disabled={hasPrior && !ack && !nothingChanged}
              onClick={() => { onConfirm && onConfirm(); onClose(); }}
              style={{
                padding: '7px 16px', borderRadius: 7, border: 0,
                background: (hasPrior && !ack && !nothingChanged)
                  ? 'color-mix(in srgb, var(--rc-green) 45%, transparent)'
                  : 'var(--rc-green)',
                color: '#fff', fontSize: 12, fontWeight: 600,
                cursor: (hasPrior && !ack && !nothingChanged) ? 'not-allowed' : 'pointer',
                fontFamily: 'inherit',
              }}>
              {hasPrior ? 'Overwrite defaults' : 'Save as default'}
            </button>
          </div>
        </>
      }>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        {nothingChanged ? (
          <div style={{
            padding: '12px 14px', borderRadius: 8,
            background: 'var(--rc-subtle)', border: '1px solid var(--rc-border-soft)',
            fontSize: 12, color: 'var(--rc-text-sub)',
          }}>
            Your current page state already matches your saved default — nothing to write.
          </div>
        ) : (
          <>
            <div style={{
              padding: '12px 14px', borderRadius: 8,
              background: 'color-mix(in srgb, var(--rc-green) 5%, var(--rc-card))',
              border: '1px solid color-mix(in srgb, var(--rc-green) 25%, var(--rc-border))',
              fontSize: 12, color: 'var(--rc-text)',
            }}>
              <div style={{ display: 'flex', gap: 8, alignItems: 'flex-start' }}>
                <Icon name="bookmark" size={14} color="var(--rc-green)" />
                <div>
                  {hasPrior
                    ? <>This will replace your current default for this report. The next time you open it, the page will come up in <b>exactly this state</b>.</>
                    : <>The next time you open this report, the page will come up in <b>exactly this state</b> — date range, metrics, charts, section layout, and any tweaks you've changed.</>
                  }
                </div>
              </div>
            </div>

            {diff.length > 0 && (
              <div>
                <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--rc-text-sub)', marginBottom: 6,
                  textTransform: 'uppercase', letterSpacing: '0.04em' }}>
                  {hasPrior ? 'Changes to your saved default' : 'Values being saved'} — {diff.length}
                </div>
                <div style={{
                  border: '1px solid var(--rc-border-soft)', borderRadius: 8,
                  maxHeight: 220, overflowY: 'auto',
                  background: 'var(--rc-card)',
                }}>
                  {diff.map((d, i) => (
                    <div key={d.key} style={{
                      padding: '8px 12px',
                      borderTop: i === 0 ? 0 : '1px solid var(--rc-border-soft)',
                      display: 'grid', gridTemplateColumns: '140px 1fr', gap: 10,
                      fontSize: 11,
                    }}>
                      <div style={{ color: 'var(--rc-text-sub)', fontFamily: 'JetBrains Mono, monospace', fontSize: 10 }}>
                        {d.key}
                      </div>
                      <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
                        {hasPrior && (
                          <div style={{ color: 'var(--rc-text-mute)', textDecoration: 'line-through', fontVariantNumeric: 'tabular-nums' }}>
                            {formatTweakValue(d.from)}
                          </div>
                        )}
                        <div style={{ color: 'var(--rc-text)', fontWeight: 500, fontVariantNumeric: 'tabular-nums' }}>
                          {formatTweakValue(d.to)}
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {hasPrior && (
              <label style={{
                display: 'flex', alignItems: 'center', gap: 8,
                fontSize: 12, color: 'var(--rc-text)',
                padding: '8px 12px', borderRadius: 7,
                background: 'color-mix(in srgb, var(--rc-amber, #f59e0b) 6%, var(--rc-card))',
                border: '1px solid color-mix(in srgb, var(--rc-amber, #f59e0b) 30%, var(--rc-border))',
                cursor: 'pointer',
              }}>
                <input type="checkbox" checked={ack} onChange={e => setAck(e.target.checked)}
                  style={{ accentColor: 'var(--rc-amber, #f59e0b)', cursor: 'pointer' }} />
                I understand this will overwrite my previous default.
              </label>
            )}
          </>
        )}
      </div>
    </P2Shell>
  );
};

function formatTweakValue(v) {
  if (v === undefined) return <span style={{ color: 'var(--rc-text-mute)', fontStyle: 'italic' }}>—</span>;
  if (v === null) return 'null';
  if (typeof v === 'boolean') return v ? 'on' : 'off';
  if (typeof v === 'string') return v;
  if (typeof v === 'number') return String(v);
  if (Array.isArray(v)) return v.length === 0 ? '[]' : `[${v.slice(0, 5).map(String).join(', ')}${v.length > 5 ? `, +${v.length - 5}` : ''}]`;
  if (typeof v === 'object') return JSON.stringify(v).slice(0, 80);
  return String(v);
}

Object.assign(window, {
  ScheduleReportModal,
  PasswordProtectionModal,
  DeleteReportConfirmModal,
  ListPasteFilterModal,
  SaveAsDefaultConfirmModal,
});
