// SettingsScreen — profile (display name + avatar), theme picker, account
// info, sign-out, danger-zone account delete. Extracted from app.jsx in Wave 7c.
//
// Exports (via Object.assign(window, { ... }) at bottom):
//   SettingsScreen
//
// External deps consumed:
//   from data modules: useAuth, getProfile, updateDisplayName,
//     uploadAvatar, removeAvatar, signOut, deleteMyAccount
//   from helpers.jsx: Page, navigate, ModalShell, ConfirmDialog,
//     relativeTime
//   from Wave 3 promotion: useTheme, useAllThemes, THEMES

(function () {

function SettingsScreen() {
  const auth = useAuth();
  const profile = getProfile(auth.user);
  const [showLogoutConfirm, setShowLogoutConfirm] = React.useState(false);
  const [activeTheme, setTheme] = useTheme();
  const allThemes = useAllThemes();

  // Delete-account flow. Type-to-confirm because this is irreversible — RPC
  // wipes every user-owned row + the auth.users entry in one transaction.
  const [showDelete, setShowDelete] = React.useState(false);
  const [deleteText, setDeleteText] = React.useState('');
  const [deletingAcct, setDeletingAcct] = React.useState(false);
  const [deleteError, setDeleteError] = React.useState(null);
  const closeDeleteDialog = () => {
    if (deletingAcct) return;
    setShowDelete(false);
    setDeleteText('');
    setDeleteError(null);
  };
  const confirmDelete = async () => {
    if (deleteText !== 'DELETE') return;
    setDeletingAcct(true);
    setDeleteError(null);
    try {
      await window.deleteMyAccount();
      // Hard-redirect so cached module state across the page is cleared.
      window.location.href = '/';
    } catch (err) {
      setDeleteError(err.message || String(err));
      setDeletingAcct(false);
    }
  };

  // Display-name section
  const [name, setName] = React.useState(profile.displayName || '');
  const [savingName, setSavingName] = React.useState(false);
  const [nameError, setNameError] = React.useState(null);
  const [nameSavedAt, setNameSavedAt] = React.useState(null);

  // Avatar section
  const [dragOver, setDragOver] = React.useState(false);
  const [uploading, setUploading] = React.useState(false);
  const [avatarError, setAvatarError] = React.useState(null);
  const fileRef = React.useRef(null);

  // If profile reloads from auth (e.g. another tab), keep field in sync only
  // when user hasn't edited it yet.
  React.useEffect(() => {
    setName((current) => current || profile.displayName || '');
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [profile.displayName]);

  const dirty = (name || '').trim() !== (profile.displayName || '').trim();

  const saveName = async (e) => {
    if (e) e.preventDefault();
    if (!dirty) return;
    setSavingName(true); setNameError(null);
    try {
      await updateDisplayName(name);
      setNameSavedAt(new Date());
    } catch (err) {
      setNameError(err.message || String(err));
    } finally {
      setSavingName(false);
    }
  };

  const pickFile = (file) => {
    if (!file) return;
    setAvatarError(null);
    setUploading(true);
    uploadAvatar(file)
      .catch((err) => setAvatarError(err.message || String(err)))
      .finally(() => setUploading(false));
  };

  const onDrop = (e) => {
    e.preventDefault();
    setDragOver(false);
    const file = e.dataTransfer?.files?.[0];
    if (file) pickFile(file);
  };

  const handleRemoveAvatar = async () => {
    if (!profile.avatarUrl) return;
    if (!confirm('Remove your profile picture?')) return;
    setAvatarError(null);
    setUploading(true);
    try {
      await removeAvatar();
    } catch (err) {
      setAvatarError(err.message || String(err));
    } finally {
      setUploading(false);
    }
  };

  const initials = (profile.displayName || profile.email || 'SB').slice(0, 2).toUpperCase();

  return (
    <Page
      crumbs={['Settings']}
    >
      <div className="cd-page" style={{ overflow: 'auto', maxWidth: 720, margin: '0 auto' }}>
        <div className="cd-page-head">
          <div className="cd-collage" aria-hidden="true">
            <span className="s1"></span><span className="s2"></span><span className="s3"></span>
          </div>
          <div className="cd-page-eyebrow">§ Settings</div>
          <h1 className="cd-page-title">Profile.</h1>
          <p className="cd-page-sub">
            How you appear in studybuddy. Only you can see this account — these are personal preferences.
          </p>
        </div>

          {/* Theme */}
          <div className="settings-card">
            <div className="card-head">
              <h2 className="card-title">Theme</h2>
              <span className="card-sub">
                Active: <strong style={{ color: 'var(--ink-strong)' }}>{(allThemes[activeTheme] || THEMES.default).label}</strong>
                {' · '}
                <a href="#" onClick={(e) => { e.preventDefault(); navigate('/themes'); }}
                  style={{ color: 'var(--accent)' }}>Browse + create →</a>
              </span>
            </div>
            <div className="settings-theme-grid">
              {Object.entries(allThemes).map(([key, t]) => (
                <button
                  key={key}
                  type="button"
                  className={"settings-theme-tile" + (activeTheme === key ? ' on' : '')}
                  onClick={() => setTheme(key)}
                  title={t.label}
                >
                  <span className="settings-theme-swatch">
                    {t.swatch.map((c, i) => (
                      <span key={i} style={{ background: c }} />
                    ))}
                  </span>
                  <span className="settings-theme-label">{t.label}</span>
                  {activeTheme === key && <span className="settings-theme-check">✓</span>}
                </button>
              ))}
            </div>
          </div>

          {/* Profile picture */}
          <div className="settings-card">
            <div className="card-head">
              <h2 className="card-title">Profile picture</h2>
              <span className="card-sub">PNG · JPG · WEBP · GIF · ≤ 5MB</span>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 18 }}>
              <div className="avatar-large">
                {profile.avatarUrl
                  ? <img src={profile.avatarUrl} alt="Profile picture" />
                  : <span>{initials}</span>}
              </div>
              <div
                className={"avatar-drop" + (dragOver ? ' dragover' : '')}
                onDragOver={(e) => { e.preventDefault(); setDragOver(true); }}
                onDragLeave={() => setDragOver(false)}
                onDrop={onDrop}
                style={{ position: 'relative' }}
              >
                <div className="head" style={{ pointerEvents: 'none' }}>
                  {uploading ? 'Uploading…' : (dragOver ? 'Release to upload' : 'Drop an image, or click to browse.')}
                </div>
                <div className="sub" style={{ pointerEvents: 'none' }}>stored privately · public read URL</div>
                <input ref={fileRef} type="file" accept="image/png,image/jpeg,image/webp,image/gif"
                  style={{
                    position: 'absolute', inset: 0, width: '100%', height: '100%',
                    opacity: 0, cursor: 'pointer',
                  }}
                  onChange={(e) => { pickFile(e.target.files?.[0]); e.target.value = ''; }}
                />
              </div>
            </div>

            {avatarError && (
              <div style={{ marginTop: 12, padding: '8px 12px', background: 'var(--brick-tint)', border: '1px solid var(--brick)', borderRadius: 6, fontSize: 12.5, color: 'var(--brick)' }}>
                {avatarError}
              </div>
            )}

            {profile.avatarUrl && (
              <div style={{ marginTop: 14, display: 'flex', gap: 8 }}>
                <button className="btn ghost sm" onClick={() => fileRef.current?.click()} disabled={uploading}>Replace</button>
                <button className="btn danger sm" onClick={handleRemoveAvatar} disabled={uploading}>Remove</button>
              </div>
            )}
          </div>

          {/* Display name */}
          <div className="settings-card">
            <div className="card-head">
              <h2 className="card-title">Display name</h2>
              <span className="card-sub">Shows in the sidebar and dashboard greeting</span>
            </div>
            <form onSubmit={saveName} style={{ display: 'flex', gap: 8, alignItems: 'flex-start' }}>
              <input
                className="input"
                type="text"
                value={name}
                placeholder={profile.email ? profile.email.split('@')[0] : 'Your name'}
                onChange={(e) => { setName(e.target.value); setNameError(null); setNameSavedAt(null); }}
                style={{ flex: 1 }}
                maxLength={80}
              />
              <button type="submit" className="btn accent sm" disabled={!dirty || savingName}>
                {savingName ? 'Saving…' : 'Save'}
              </button>
            </form>
            {nameError && (
              <div style={{ marginTop: 10, padding: '8px 12px', background: 'var(--brick-tint)', border: '1px solid var(--brick)', borderRadius: 6, fontSize: 12.5, color: 'var(--brick)' }}>
                {nameError}
              </div>
            )}
            {nameSavedAt && !nameError && !dirty && (
              <div style={{ marginTop: 10, fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--ink-mute)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>
                Saved {relativeTime(nameSavedAt.toISOString())}
              </div>
            )}
          </div>

          {/* Account (read-only) */}
          <div className="settings-card">
            <div className="card-head">
              <h2 className="card-title">Account</h2>
              <span className="card-sub">Identity in Supabase auth</span>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', padding: '4px 0', fontSize: 13.5 }}>
              <span style={{ color: 'var(--ink-soft)' }}>Email</span>
              <span className="mono" style={{ color: 'var(--ink-strong)' }}>{profile.email || '—'}</span>
            </div>
            <div style={{ marginTop: 14, display: 'flex', justifyContent: 'flex-end' }}>
              <button className="btn sm" onClick={() => setShowLogoutConfirm(true)}>Sign out</button>
            </div>
          </div>

          {/* Danger zone — permanently delete the account */}
          <div className="settings-card danger-zone">
            <div className="card-head">
              <h2 className="card-title">Danger zone</h2>
              <span className="card-sub">Irreversible</span>
            </div>
            <p style={{ margin: '4px 0 14px', fontSize: 13.5, color: 'var(--ink-soft)', lineHeight: 1.5 }}>
              Permanently delete your account and every guide, note, file, event,
              and flashcard you've made. This cannot be undone.
            </p>
            <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
              <button
                className="btn sm danger"
                onClick={() => setShowDelete(true)}
              >
                Delete account
              </button>
            </div>
          </div>
      </div>

      {showLogoutConfirm && (
        <ConfirmDialog
          title="Sign out?"
          message={`You'll be signed out of ${profile.email || 'this account'}. Your data stays on the server — sign back in any time.`}
          confirmLabel="Sign out"
          tone="danger"
          onConfirm={async () => { await signOut(); setShowLogoutConfirm(false); }}
          onCancel={() => setShowLogoutConfirm(false)}
        />
      )}

      {showDelete && (
        <ModalShell onClose={closeDeleteDialog}>
          <div className="delete-account-dialog">
            <h2>Delete your account?</h2>
            <p className="warn">
              This removes <strong>everything</strong> — guides, notes, files, events,
              flashcards, sharing — and disconnects you from {profile.email || 'this account'}.
              You can't undo it.
            </p>
            <label className="delete-confirm-label">
              <span>Type <strong>DELETE</strong> to confirm</span>
              <input
                type="text"
                autoComplete="off"
                autoFocus
                value={deleteText}
                onChange={(e) => setDeleteText(e.target.value)}
                onKeyDown={(e) => { if (e.key === 'Enter' && deleteText === 'DELETE') confirmDelete(); }}
                placeholder="DELETE"
                disabled={deletingAcct}
              />
            </label>
            {deleteError && <div className="delete-error">{deleteError}</div>}
            <div className="delete-actions">
              <button className="btn sm" onClick={closeDeleteDialog} disabled={deletingAcct}>Cancel</button>
              <button
                className="btn sm danger"
                onClick={confirmDelete}
                disabled={deleteText !== 'DELETE' || deletingAcct}
              >
                {deletingAcct ? 'Deleting…' : 'Delete account'}
              </button>
            </div>
          </div>
        </ModalShell>
      )}
    </Page>
  );
}

// ─── Exports ───────────────────────────────────────────────────────────────

Object.assign(window, { SettingsScreen });

})();
