// Settings — bottom-sheet overlay for app preferences, data, and notifications.

function Settings({ open, onClose, tweaks, setTweak, profile, onUpdateProfile, account, onOpenAuth, onSignOut, onUpgrade }) {
  const { Icons } = window;
  const asset = window.assetPath || ((name) => `assets/${name}`);
  const [notifStatus, setNotifStatus] = React.useState(() =>
    typeof Notification !== 'undefined' ? Notification.permission : 'unsupported'
  );
  const [importErr, setImportErr] = React.useState('');
  const fileRef = React.useRef(null);
  // PRD-007 profile name draft
  const [nameDraft, setNameDraft] = React.useState(profile?.name || '');
  // PRD-006 notification lead time (minutes)
  const [notifLead, setNotifLead] = React.useState(() => { try { return parseInt(window.DB?.load('notifLead', 0), 10) || 0; } catch { return 0; } });

  React.useEffect(() => { if (open) setNameDraft(profile?.name || ''); }, [open, profile?.name]);

  if (!open) return null;

  const saveName = () => { const n = nameDraft.trim(); if (n && onUpdateProfile) onUpdateProfile({ name: n }); };
  const pickLead = (m) => { setNotifLead(m); try { window.DB?.save('notifLead', m); } catch {} };
  const NOTIF_LEAD_OPTS = [[0, 'بدون'], [15, '۱۵ دقیقه'], [30, '۳۰ دقیقه'], [60, '۱ ساعت']];

  const ACCENT_OPTIONS = ['#1F8A8A', '#C97A1F', '#5A7A3A', '#B23A48', '#0F5A5A'];
  const ACCENT_NAMES   = ['فیروزه‌ای', 'زعفرانی', 'سبز', 'قرمز', 'عمیق'];

  const requestNotif = async () => {
    if (typeof Notification === 'undefined') return;
    const result = await Notification.requestPermission();
    setNotifStatus(result);
  };

  const testNotif = () => {
    if (Notification.permission !== 'granted') return;
    new Notification('لاگی | Logi', {
      body: 'اعلان‌ها فعال هستند ✓',
      icon: asset('favicon.svg'),
      dir: 'rtl',
      lang: 'fa',
    });
  };

  const exportData = () => {
    const json = window.DB.export();
    const blob = new Blob([json], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `logi-backup-${new Date().toISOString().slice(0,10)}.json`;
    a.click();
    URL.revokeObjectURL(url);
  };

  const importData = (e) => {
    const file = e.target.files?.[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = (ev) => {
      try {
        window.DB.importData(ev.target.result);
        setImportErr('');
        window.location.reload();
      } catch {
        setImportErr('فایل نامعتبر است. لطفاً فایل پشتیبان درستی انتخاب کنید.');
      }
    };
    reader.readAsText(file);
    e.target.value = '';
  };

  const clearAll = () => {
    window.confirmAction('تمام داده‌های لاگی پاک شود؟ این کار برگشت‌پذیر نیست.', () => {
      window.DB.clearAll();
      window.location.reload();
    });
  };

  const sectionTitleStyle = {
    font: "600 12px 'Estedad', sans-serif",
    color: 'var(--ink-3)',
    letterSpacing: '0.06em',
    textTransform: 'uppercase',
    marginBottom: 12,
    marginTop: 24,
  };

  const rowStyle = {
    display: 'flex', alignItems: 'center', justifyContent: 'space-between',
    padding: '14px 0', borderBottom: '1px solid var(--c-border-xs)',
    direction: 'rtl',
  };

  const labelStyle = {
    font: "500 14px 'Estedad', sans-serif",
    color: 'var(--ink)',
  };

  const subStyle = {
    font: "400 12px 'Estedad', sans-serif",
    color: 'var(--ink-3)',
    marginTop: 2,
  };

  const toggleStyle = (on) => ({
    width: 44, height: 26, borderRadius: 999,
    background: on ? 'var(--firoozeh)' : 'var(--c-inactive)',
    border: 'none', cursor: 'pointer', position: 'relative',
    transition: 'background 180ms', flexShrink: 0,
  });

  const thumbStyle = (on) => ({
    position: 'absolute', top: 3, width: 20, height: 20,
    borderRadius: '50%', background: '#fff',
    transition: 'right 180ms, left 180ms',
    ...(on ? { right: 3 } : { right: 21 }),
  });

  const btnStyle = (variant = 'ghost') => ({
    padding: '10px 18px', borderRadius: 10, cursor: 'pointer',
    font: "500 13px 'Estedad', sans-serif",
    border: 'none',
    ...(variant === 'primary'
      ? { background: 'var(--firoozeh)', color: '#fff' }
      : variant === 'danger'
      ? { background: 'rgba(178,58,72,0.08)', color: 'var(--garnet)', border: '1px solid rgba(178,58,72,0.25)' }
      : { background: 'var(--surface)', color: 'var(--ink-2)', border: '1px solid var(--c-border-sm)' }),
  });

  const inputStyle = {
    flex: 1, minWidth: 0, boxSizing: 'border-box', background: 'var(--surface)',
    border: '1px solid var(--c-border-sm)', borderRadius: 10, padding: '10px 12px',
    font: "400 14px 'Estedad', sans-serif", color: 'var(--ink)',
    direction: 'rtl', textAlign: 'right', outline: 'none',
  };
  const chipStyle = (on) => ({
    padding: '8px 12px', borderRadius: 999, cursor: 'pointer',
    font: "500 13px 'Estedad', sans-serif",
    border: `1px solid ${on ? 'var(--firoozeh)' : 'var(--c-border-sm)'}`,
    background: on ? 'var(--firoozeh-soft)' : 'var(--surface)',
    color: on ? 'var(--firoozeh-deep)' : 'var(--ink-2)',
  });

  const notifLabel = { unsupported: 'پشتیبانی نمی‌شود', denied: 'رد شده', default: 'درخواست نشده', granted: 'فعال' }[notifStatus] || '';

  return (
    <div
      style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.45)', backdropFilter: 'blur(4px)', WebkitBackdropFilter: 'blur(4px)', zIndex: 700, display: 'flex', alignItems: 'flex-end', justifyContent: 'center', direction: 'rtl' }}
      onClick={onClose}
    >
      <div
        style={{ width: '100%', maxWidth: 600, background: 'var(--paper)', borderRadius: '22px 22px 0 0', maxHeight: '88vh', overflowY: 'auto', boxShadow: '0 -8px 32px rgba(0,0,0,0.18)' }}
        onClick={e => e.stopPropagation()}
      >
        <div style={{ width: 36, height: 4, borderRadius: 999, background: 'var(--c-inactive)', margin: '12px auto 0' }} />

        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '16px 20px 0' }}>
          <span style={{ font: "600 17px 'Estedad', sans-serif", color: 'var(--ink)' }}>تنظیمات</span>
          <button onClick={onClose} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--ink-3)', padding: 4 }}>
            <Icons.X size={20} />
          </button>
        </div>

        <div style={{ padding: '0 20px calc(32px + env(safe-area-inset-bottom))' }}>

          {/* Account / subscription */}
          <div style={sectionTitleStyle}>حساب کاربری</div>
          {account && account.user ? (
            <>
              <div style={{ ...rowStyle, gap: 10 }}>
                <div style={{ width: 40, height: 40, borderRadius: 999, flexShrink: 0, background: 'var(--firoozeh-soft)', color: 'var(--firoozeh-deep)', display: 'grid', placeItems: 'center', font: "700 16px 'Estedad', sans-serif" }}>
                  {(account.user.name || account.user.phone || '؟').toString().trim()[0]}
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={labelStyle}>{account.user.name || 'کاربر لاگی'}</div>
                  <div style={subStyle} dir="ltr">{account.user.phone || account.user.email || ''}</div>
                </div>
                <button style={btnStyle('danger')} onClick={onSignOut}>خروج</button>
              </div>
              <div style={{ ...rowStyle, borderBottom: 'none' }}>
                <div>
                  <div style={labelStyle}>اشتراک</div>
                  <div style={subStyle}>
                    {account.sub && account.sub.status === 'active'
                      ? `فعال — تا ${account.sub.expiresAt ? account.sub.expiresAt.slice(0,10) : ''}`
                      : 'بدون اشتراک فعال'}
                  </div>
                </div>
                <button style={btnStyle('primary')} onClick={onUpgrade}>
                  {account.sub && account.sub.status === 'active' ? 'تمدید' : 'ارتقا'}
                </button>
              </div>
            </>
          ) : (
            <div style={{ ...rowStyle, borderBottom: 'none' }}>
              <div>
                <div style={labelStyle}>ورود به حساب</div>
                <div style={subStyle}>برای همگام‌سازی بین دستگاه‌ها و اشتراک</div>
              </div>
              <button style={btnStyle('primary')} onClick={onOpenAuth}>ورود / ثبت‌نام</button>
            </div>
          )}

          {/* Profile (PRD-007) */}
          <div style={sectionTitleStyle}>پروفایل</div>
          <div style={{ ...rowStyle, gap: 10 }}>
            <div style={{ width: 40, height: 40, borderRadius: 999, flexShrink: 0, background: 'var(--firoozeh-soft)', color: 'var(--firoozeh-deep)', display: 'grid', placeItems: 'center', font: "700 16px 'Estedad', sans-serif" }}>
              {(nameDraft.trim()[0] || profile?.avatar || 'ک')}
            </div>
            <input
              style={inputStyle}
              value={nameDraft}
              onChange={e => setNameDraft(e.target.value)}
              onBlur={saveName}
              onKeyDown={e => e.key === 'Enter' && (e.target.blur())}
              placeholder="نام تو…"
              maxLength={30}
            />
            <button style={btnStyle('primary')} onClick={saveName}>ذخیره</button>
          </div>

          {/* Display */}
          <div style={sectionTitleStyle}>نمایش</div>

          <div style={rowStyle}>
            <div><div style={labelStyle}>حالت تاریک</div></div>
            <button style={toggleStyle(tweaks?.dark)} onClick={() => setTweak('dark', !tweaks?.dark)}>
              <div style={thumbStyle(tweaks?.dark)} />
            </button>
          </div>

          <div style={rowStyle}>
            <div><div style={labelStyle}>بافت کاغذ</div></div>
            <button style={toggleStyle(tweaks?.paperGrain !== false)} onClick={() => setTweak('paperGrain', tweaks?.paperGrain === false)}>
              <div style={thumbStyle(tweaks?.paperGrain !== false)} />
            </button>
          </div>

          <div style={{ ...rowStyle, flexDirection: 'column', alignItems: 'flex-start', gap: 10 }}>
            <div style={labelStyle}>رنگ تأکید</div>
            <div style={{ display: 'flex', gap: 10 }}>
              {ACCENT_OPTIONS.map((col, i) => (
                <button key={col} title={ACCENT_NAMES[i]}
                  onClick={() => setTweak('accent', col)}
                  style={{ width: 32, height: 32, borderRadius: '50%', background: col, border: tweaks?.accent === col ? '3px solid var(--ink)' : '3px solid transparent', cursor: 'pointer', outline: 'none', transition: 'border 120ms' }}
                />
              ))}
            </div>
          </div>

          {/* Data */}
          <div style={sectionTitleStyle}>داده‌ها</div>

          <div style={rowStyle}>
            <div>
              <div style={labelStyle}>صادر کردن داده‌ها</div>
              <div style={subStyle}>دانلود فایل پشتیبان JSON</div>
            </div>
            <button style={btnStyle()} onClick={exportData}>دانلود</button>
          </div>

          <div style={rowStyle}>
            <div>
              <div style={labelStyle}>وارد کردن داده‌ها</div>
              <div style={subStyle}>بارگذاری فایل پشتیبان</div>
            </div>
            <button style={btnStyle()} onClick={() => fileRef.current?.click()}>انتخاب فایل</button>
            <input ref={fileRef} type="file" accept=".json" style={{ display: 'none' }} onChange={importData} />
          </div>
          {importErr && <div style={{ color: '#B23A48', font: "400 13px 'Estedad', sans-serif", marginBottom: 8, direction: 'rtl' }}>{importErr}</div>}

          <div style={{ ...rowStyle, borderBottom: 'none' }}>
            <div>
              <div style={labelStyle}>پاک کردن همه داده‌ها</div>
              <div style={subStyle}>برگشت‌ناپذیر است</div>
            </div>
            <button style={btnStyle('danger')} onClick={clearAll}>پاک کن</button>
          </div>

          {/* Notifications */}
          <div style={sectionTitleStyle}>اعلان‌ها</div>

          <div style={rowStyle}>
            <div>
              <div style={labelStyle}>وضعیت اعلان</div>
              <div style={subStyle}>{notifLabel}</div>
            </div>
            {notifStatus !== 'granted' && notifStatus !== 'denied' && notifStatus !== 'unsupported' && (
              <button style={btnStyle('primary')} onClick={requestNotif}>فعال‌سازی</button>
            )}
            {notifStatus === 'granted' && (
              <button style={btnStyle()} onClick={testNotif}>تست</button>
            )}
          </div>

          {/* PRD-006: lead-time reminder */}
          <div style={{ ...rowStyle, flexDirection: 'column', alignItems: 'flex-start', gap: 10 }}>
            <div>
              <div style={labelStyle}>یادآوری قبل از سررسید</div>
              <div style={subStyle}>چند دقیقه قبل از زمان کار هم یادآوری شود</div>
            </div>
            <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
              {NOTIF_LEAD_OPTS.map(([m, lbl]) => (
                <button key={m} style={chipStyle(notifLead === m)} onClick={() => pickLead(m)}>{lbl}</button>
              ))}
            </div>
          </div>

          {/* About */}
          <div style={sectionTitleStyle}>درباره</div>
          <div style={{ ...rowStyle, borderBottom: 'none', flexDirection: 'column', alignItems: 'flex-start', gap: 4 }}>
            <div style={labelStyle}>لاگی | Logi</div>
            <div style={subStyle}>مغز دوم شخصی فارسی — نسخه ۱.۰</div>
            <div style={subStyle}>تسک · مالی · حافظه · دستیار هوشمند</div>
          </div>

        </div>
      </div>
    </div>
  );
}

window.Settings = Settings;
