// settings.jsx — In-app settings screen (theme, notifications, etc.)

const { useState: useStateSet, useEffect: useEffectSet } = React;
const { Card, TopBar, DisplayHeading, Icon } = window.LAUNCH_SCREENS_1;

// Darken a hex color by `amt` (-100..100). Used to render planet shading.
function shadeColor(hex, amt) {
  const m = hex.replace('#', '');
  const num = parseInt(m, 16);
  let r = (num >> 16) + Math.round(amt * 2.55);
  let g = ((num >> 8) & 0xff) + Math.round(amt * 2.55);
  let b = (num & 0xff) + Math.round(amt * 2.55);
  r = Math.max(0, Math.min(255, r));
  g = Math.max(0, Math.min(255, g));
  b = Math.max(0, Math.min(255, b));
  return '#' + [r, g, b].map(x => x.toString(16).padStart(2, '0')).join('');
}

// ────────────────────────────────────────────────────────
// SettingsScreen — accessed from Profile
// ────────────────────────────────────────────────────────
// The Subscription row used to show a hardcoded "Orbit · $99/mo · renews Jun 11":
// a plan that doesn't exist, at a price we don't charge, with an invented date.
// Read the real one instead — and deliberately without a price, so this can
// never contradict what the App Store / Play actually bills in each country.
function planSubtitleFrom(ent) {
  const plan = (ent && ent.plan) || 'free';
  if (plan === 'free' || !ent.active) return 'Free · tap to upgrade';
  const name = plan === 'vip' ? 'VIP' : 'Basic';
  if (!ent.expiresAt) return name;
  try {
    const d = new Date(ent.expiresAt).toLocaleDateString('en-US',
      { month: 'short', day: '2-digit', year: 'numeric' }).toUpperCase();
    return `${name} · renews ${d}`;
  } catch (e) { return name; }
}

function SettingsScreen({ theme, onBack, dark, onChangeDark, accent, onChangeAccent, onOpenAdmin, onOpenCoachQueue, onEditProfile, onOpenSubscription }) {
  const ent = window.LAUNCH_USER.usePlan
    ? window.LAUNCH_USER.usePlan()
    : { plan: 'free', active: false, expiresAt: null };
  const planSubtitle = planSubtitleFrom(ent);

  const [notifications, setNotifications] = useStateSet({
    streak: true,
    lesson: true,
    feedback: true,
    leaderboard: false,
    drops: true,
  });

  const toggleNotif = (key) => setNotifications(v => ({ ...v, [key]: !v[key] }));

  // Which support page is open as an overlay (null = none).
  const [supportPanel, setSupportPanel] = useStateSet(null);
  // Delete-account confirmation flow open?
  const [showDelete, setShowDelete] = useStateSet(false);

  // ── Store diagnostics (hidden: five taps on the version line) ─────────────
  // Text of the panel, or null when it's closed. Kept out of the way because
  // it's a developer tool, not a feature.
  const [diagTaps, setDiagTaps] = useStateSet(0);
  const [storeDiag, setStoreDiag] = useStateSet(null);

  // What the native shell actually exposes. Answers, in order: are we native,
  // did the RevenueCat plugin make it into the build, and is the public key
  // loaded? Any one of those being false is what makes the Plans screen say
  // memberships are unavailable.
  const runStoreDiag = () => {
    const lines = [];
    const C = window.Capacitor || null;
    const cfg = window.LAUNCH_CONFIG || {};
    const I = window.LAUNCH_IAP || null;

    let platform = 'web';
    let native = false;
    try { platform = C && C.getPlatform ? C.getPlatform() : 'web'; } catch (e) {}
    try { native = !!(C && C.isNativePlatform && C.isNativePlatform()); } catch (e) {}

    let available = null;
    try {
      available = (C && typeof C.isPluginAvailable === 'function')
        ? C.isPluginAvailable('Purchases') : 'no isPluginAvailable()';
    } catch (e) { available = 'threw: ' + e.message; }

    let registered = [];
    try { registered = Object.keys((C && C.Plugins) || {}); } catch (e) {}

    const key = cfg.REVENUECAT_IOS_KEY || '';
    lines.push('Capacitor      : ' + (C ? 'present' : 'MISSING'));
    lines.push('platform       : ' + platform);
    lines.push('isNative       : ' + native);
    lines.push("plugin 'Purchases': " + available);
    lines.push('plugins loaded : ' + (registered.length ? registered.join(', ') : '(none)'));
    lines.push('RevenueCat key : ' + (key ? key.slice(0, 10) + '… (' + key.length + ' chars)' : 'EMPTY'));
    lines.push('LAUNCH_IAP     : ' + (I ? 'loaded' : 'MISSING'));
    lines.push('isAvailable()  : ' + (I && I.isAvailable ? I.isAvailable() : 'n/a'));
    lines.push('canBuyInApp()  : ' + (window.LAUNCH_USER ? window.LAUNCH_USER.canBuyInApp() : 'n/a'));

    // How the plugin proxy was obtained, and what broke if it wasn't. This is
    // the part that told us registerPlugin was failing while the plugin itself
    // was perfectly present.
    if (I && typeof I.diagnostics === 'function') {
      let d = null;
      try { d = I.diagnostics(); } catch (e) { d = { pluginError: 'diagnostics threw: ' + e.message }; }
      lines.push('');
      lines.push('registerPlugin : ' + (d.hasRegisterPlugin ? 'is a function' : 'MISSING'));
      lines.push('plugin proxy   : ' + (d.pluginResolved ? 'resolved via ' + d.pluginSource : 'NOT RESOLVED'));
      lines.push('plugin error   : ' + (d.pluginError || 'none'));
      lines.push('configured for : ' + (d.configuredFor || '(not yet)'));
      lines.push('last purchase  : ' + (d.lastPurchase || '(none this session)'));
    }
    lines.push('');
    lines.push('Tap TEST STORE to configure the SDK and ask the store for');
    lines.push('the products. That is what fails when the products are not');
    lines.push('set up in App Store Connect.');
    setStoreDiag(lines.join('\n'));
  };

  // Go one step further: start the SDK for this user and read the offerings.
  // Separated from the summary above because it hits the network and the
  // store, and its failure means something different (products/entitlements
  // missing rather than a broken build).
  const runStoreTest = async () => {
    const I = window.LAUNCH_IAP;
    const out = [];
    if (!I || !I.isAvailable || !I.isAvailable()) {
      setStoreDiag('Store unavailable — the plugin or the key is missing, so\nthere is nothing to test yet. See the summary above.');
      return;
    }
    setStoreDiag('Testing the store…');
    try {
      const prices = await window.LAUNCH_USER.iapPrices();
      out.push('plan prices    : ' + JSON.stringify(prices));
    } catch (e) { out.push('plan prices    : threw ' + e.message); }
    try {
      const items = await window.LAUNCH_USER.iapItemPrices();
      out.push('item prices    : ' + JSON.stringify(items));
    } catch (e) { out.push('item prices    : threw ' + e.message); }
    out.push('');
    out.push('Empty prices mean the SDK is fine but the store returned no');
    out.push('products — create them in App Store Connect and attach them');
    out.push('to the RevenueCat offering.');
    setStoreDiag(out.join('\n'));
  };

  const Row = ({ icon, title, sub, right, onClick }) => {
    const clickable = typeof onClick === 'function';
    const Tag = clickable ? 'button' : 'div';
    return (
      <Tag
        onClick={onClick}
        style={{
          width: '100%', textAlign: 'left', font: 'inherit',
          padding: '14px 14px', display: 'flex', alignItems: 'center', gap: 14,
          background: 'transparent', border: 'none',
          cursor: clickable ? 'pointer' : 'default',
        }}>
        {icon && (
          <div style={{
            width: 36, height: 36, borderRadius: 10,
            background: theme.surface2,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            flexShrink: 0,
          }}>{icon}</div>
        )}
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontFamily: theme.fontBody, fontSize: 14, color: theme.text, fontWeight: 600 }}>
            {title}
          </div>
          {sub && (
            <div style={{ fontFamily: theme.fontMono, fontSize: 10, color: theme.muted, letterSpacing: 0.5, marginTop: 2, fontWeight: 600 }}>
              {sub.toUpperCase()}
            </div>
          )}
        </div>
        {right}
      </Tag>
    );
  };

  const Toggle = ({ on, onChange }) => (
    <button onClick={onChange} style={{
      width: 46, height: 28, borderRadius: 99,
      background: on ? theme.accent : theme.surface2,
      border: 'none', cursor: 'pointer', position: 'relative',
      transition: 'background .2s',
      padding: 0, flexShrink: 0,
    }}>
      <div style={{
        position: 'absolute', top: 3, left: on ? 21 : 3,
        width: 22, height: 22, borderRadius: 99,
        background: '#fff', boxShadow: '0 2px 4px rgba(0,0,0,0.2)',
        transition: 'left .2s',
      }} />
    </button>
  );

  const Group = ({ label, children }) => (
    <div style={{ padding: `${theme.gap + 4}px ${theme.pad}px 0` }}>
      <div style={{
        fontFamily: theme.fontMono, fontSize: 11, color: theme.muted,
        letterSpacing: 1, fontWeight: 600, marginBottom: 10,
      }}>{label}</div>
      <Card theme={theme} style={{ overflow: 'hidden' }}>
        {React.Children.map(children, (child, i) => (
          <React.Fragment key={i}>
            {i > 0 && <div style={{ height: 1, background: theme.border, marginLeft: 64 }} />}
            {child}
          </React.Fragment>
        ))}
      </Card>
    </div>
  );

  return (
    <div style={{ paddingBottom: 110 }}>
      {/* Top bar */}
      <div style={{
        paddingTop: 58, paddingBottom: 8, paddingLeft: theme.pad, paddingRight: theme.pad,
        display: 'flex', alignItems: 'center', gap: 12,
      }}>
        <button onClick={onBack} style={{
          width: 38, height: 38, borderRadius: 12,
          background: theme.surface, border: `1px solid ${theme.border}`,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          cursor: 'pointer',
        }}>
          <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
            <path d="M9 2L4 7l5 5" stroke={theme.text} strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </button>
      </div>

      <div style={{ padding: `4px ${theme.pad}px 0` }}>
        <div style={{ fontFamily: theme.fontMono, fontSize: 10, color: theme.muted, letterSpacing: 1, fontWeight: 700 }}>
          ★ MISSION CONFIG
        </div>
        <DisplayHeading theme={theme} size={36}>SETTINGS</DisplayHeading>
      </div>

      {/* APPEARANCE — the headliner */}
      <Group label="APPEARANCE">
        {/* Theme picker — segmented control with previews */}
        <div style={{ padding: 14 }}>
          <div style={{
            fontFamily: theme.fontBody, fontSize: 14, color: theme.text,
            fontWeight: 600, marginBottom: 4,
          }}>Theme</div>
          <div style={{
            fontFamily: theme.fontMono, fontSize: 10, color: theme.muted,
            letterSpacing: 0.5, fontWeight: 600, marginBottom: 14,
          }}>CHOOSE HOW LAUNCH LOOKS</div>
          <div style={{
            display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10,
          }}>
            {[
              { id: 'light', dark: false, l: 'LIGHT', icon: '☀' },
              { id: 'dark',  dark: true,  l: 'DARK',  icon: '☾' },
              { id: 'auto',  dark: null,  l: 'AUTO',  icon: '◐', sub: 'SYSTEM' },
            ].map(opt => {
              const isActive = opt.id === 'auto' ? false : (dark === opt.dark);
              return (
                <button
                  key={opt.id}
                  onClick={() => opt.id !== 'auto' && onChangeDark(opt.dark)}
                  disabled={opt.id === 'auto'}
                  style={{
                    padding: 0, border: 'none', cursor: opt.id === 'auto' ? 'not-allowed' : 'pointer',
                    borderRadius: 14, overflow: 'hidden',
                    background: 'transparent',
                    boxShadow: isActive ? `0 0 0 2px ${theme.accent}` : `0 0 0 1px ${theme.border}`,
                    transition: 'box-shadow .15s',
                    opacity: opt.id === 'auto' ? 0.5 : 1,
                  }}>
                  {/* Mini preview */}
                  <div style={{
                    height: 76, position: 'relative',
                    background: opt.dark === true ? '#0A0A0A' :
                                opt.dark === false ? '#EDE7DC' :
                                'linear-gradient(135deg, #EDE7DC 50%, #0A0A0A 50%)',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                  }}>
                    {/* Status bar pill */}
                    <div style={{
                      position: 'absolute', top: 8, left: '50%', transform: 'translateX(-50%)',
                      width: 18, height: 4, borderRadius: 99,
                      background: opt.dark === false ? '#0A0A0A' : '#fff',
                      opacity: 0.6,
                    }} />
                    {/* Sample type */}
                    <div style={{
                      fontFamily: theme.fontDisplay, fontSize: 26,
                      color: opt.dark === false ? '#0A0A0A' : '#fff',
                      letterSpacing: 0.5,
                    }}>{opt.icon}</div>
                    {/* Sample accent dot */}
                    <div style={{
                      position: 'absolute', bottom: 8, left: '50%', transform: 'translateX(-50%)',
                      width: 18, height: 4, borderRadius: 99, background: theme.accent,
                    }} />
                  </div>
                  <div style={{
                    padding: '8px 6px', background: theme.surface,
                    fontFamily: theme.fontMono, fontSize: 10, fontWeight: 700,
                    letterSpacing: 1, color: isActive ? theme.accent : theme.text,
                    textAlign: 'center',
                  }}>{opt.l}{isActive && ' ✓'}</div>
                  {opt.sub && (
                    <div style={{
                      padding: '2px 6px 6px', background: theme.surface,
                      fontFamily: theme.fontMono, fontSize: 8, color: theme.faint,
                      letterSpacing: 0.5, textAlign: 'center', fontWeight: 600,
                    }}>{opt.sub}</div>
                  )}
                </button>
              );
            })}
          </div>
        </div>

        <Row
          icon={
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
              <circle cx="12" cy="12" r="4" stroke={theme.text} strokeWidth="2"/>
              <path d="M12 2v3M12 19v3M2 12h3M19 12h3M4.5 4.5l2 2M17.5 17.5l2 2M4.5 19.5l2-2M17.5 6.5l2-2" stroke={theme.text} strokeWidth="2" strokeLinecap="round"/>
            </svg>
          }
          title="Reduce motion"
          sub="Less animation on splash and transitions"
          right={<Toggle on={false} onChange={() => {}} />}
        />
      </Group>

      {/* ACCENT */}
      <Group label="ACCENT COLOR">
        <div style={{ padding: 14 }}>
          <div style={{
            fontFamily: theme.fontMono, fontSize: 10, color: theme.muted,
            letterSpacing: 0.5, fontWeight: 600, marginBottom: 12,
          }}>★ PICK YOUR PLANET</div>
          <div style={{ display: 'flex', gap: 10, justifyContent: 'space-between' }}>
            {[
              { v: '#C72820', l: 'MARS',    sub: 'RED PLANET' },
              { v: '#4A7FD8', l: 'NEPTUNE', sub: 'DEEP BLUE' },
              { v: '#7A5AE0', l: 'NEBULA',  sub: 'ULTRAVIOLET' },
              { v: '#E8A736', l: 'SOLAR',   sub: 'STARLIGHT' },
            ].map(c => {
              const on = accent === c.v;
              return (
                <button
                  key={c.v}
                  onClick={() => onChangeAccent && onChangeAccent(c.v)}
                  style={{
                    flex: 1, padding: 0, border: 'none', cursor: 'pointer',
                    background: 'transparent', textAlign: 'center',
                  }}>
                  <div style={{
                    width: 52, height: 52, borderRadius: '50%',
                    margin: '0 auto',
                    background: `radial-gradient(circle at 35% 30%, ${c.v} 0%, ${c.v} 40%, ${shadeColor(c.v, -55)} 100%)`,
                    position: 'relative',
                    boxShadow: on
                      ? `0 0 0 3px ${theme.bg}, 0 0 0 5px ${c.v}, 0 0 24px ${c.v}55`
                      : `inset 0 -8px 16px rgba(0,0,0,0.35), 0 4px 12px ${c.v}30`,
                    transition: 'box-shadow .15s',
                  }}>
                    {/* highlight */}
                    <div style={{
                      position: 'absolute', top: 8, left: 12,
                      width: 12, height: 8, borderRadius: '50%',
                      background: 'rgba(255,255,255,0.45)',
                      filter: 'blur(2px)',
                    }} />
                    {/* saturn-style ring for Nebula */}
                    {c.l === 'NEBULA' && (
                      <div style={{
                        position: 'absolute', top: '50%', left: '-15%',
                        width: '130%', height: 6,
                        transform: 'translateY(-50%) rotate(-18deg)',
                        background: `linear-gradient(90deg, transparent 10%, ${c.v}cc 30%, ${c.v}cc 70%, transparent 90%)`,
                        borderRadius: 99,
                        boxShadow: `0 0 6px ${c.v}88`,
                      }} />
                    )}
                  </div>
                  <div style={{
                    fontFamily: theme.fontMono, fontSize: 9, fontWeight: 700,
                    letterSpacing: 0.8, color: on ? theme.text : theme.muted,
                    marginTop: 10,
                  }}>{c.l}{on && ' ✓'}</div>
                  <div style={{
                    fontFamily: theme.fontMono, fontSize: 8,
                    letterSpacing: 0.6, color: theme.faint, fontWeight: 600,
                    marginTop: 2,
                  }}>{c.sub}</div>
                </button>
              );
            })}
          </div>
        </div>
      </Group>

      {/* NOTIFICATIONS */}
      <Group label="NOTIFICATIONS">
        <Row
          icon={<span style={{ fontSize: 18 }}>🔥</span>}
          title="Streak reminders"
          sub="Daily nudge before you break"
          right={<Toggle on={notifications.streak} onChange={() => toggleNotif('streak')} />}
        />
        <Row
          icon={<span style={{ fontSize: 18 }}>📚</span>}
          title="Today's lesson"
          sub="Drop time: 9:00 AM"
          right={<Toggle on={notifications.lesson} onChange={() => toggleNotif('lesson')} />}
        />
        <Row
          icon={<span style={{ fontSize: 18 }}>💬</span>}
          title="Feedback & reviews"
          sub="When your work gets a response"
          right={<Toggle on={notifications.feedback} onChange={() => toggleNotif('feedback')} />}
        />
        <Row
          icon={<span style={{ fontSize: 18 }}>🏆</span>}
          title="Leaderboard updates"
          sub="Weekly rankings + position changes"
          right={<Toggle on={notifications.leaderboard} onChange={() => toggleNotif('leaderboard')} />}
        />
        <Row
          icon={<span style={{ fontSize: 18 }}>🎵</span>}
          title="Squad drops"
          sub="New tracks from people you follow"
          right={<Toggle on={notifications.drops} onChange={() => toggleNotif('drops')} />}
        />
      </Group>

      {/* ACCOUNT */}
      <Group label="ACCOUNT">
        <Row
          icon={
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
              <circle cx="12" cy="8" r="4" stroke={theme.text} strokeWidth="2"/>
              <path d="M4 21c0-4 4-7 8-7s8 3 8 7" stroke={theme.text} strokeWidth="2" strokeLinecap="round"/>
            </svg>
          }
          title="Edit profile"
          sub="Handle · bio · genres"
          onClick={onEditProfile}
          right={
            <svg width="8" height="14" viewBox="0 0 8 14" fill="none">
              <path d="M1 1l6 6-6 6" stroke={theme.faint} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          }
        />
        <Row
          icon={
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
              <path d="M4 7h16v12H4V7zM4 7l2-3h12l2 3" stroke={theme.text} strokeWidth="2" strokeLinejoin="round"/>
              <path d="M9 12h6" stroke={theme.text} strokeWidth="2" strokeLinecap="round"/>
            </svg>
          }
          title="Subscription"
          sub={planSubtitle}
          onClick={onOpenSubscription}
          right={
            <svg width="8" height="14" viewBox="0 0 8 14" fill="none">
              <path d="M1 1l6 6-6 6" stroke={theme.faint} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          }
        />
        <button onClick={() => setShowDelete(true)} style={{
          width: '100%', textAlign: 'left', font: 'inherit',
          padding: '14px 14px', display: 'flex', alignItems: 'center', gap: 14,
          background: 'transparent', border: 'none', cursor: 'pointer',
        }}>
          <div style={{
            width: 36, height: 36, borderRadius: 10, background: '#E5484D22',
            display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
          }}>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
              <path d="M4 7h16M9 7V5a1 1 0 011-1h4a1 1 0 011 1v2M6 7l1 13h10l1-13" stroke="#E5484D" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontFamily: theme.fontBody, fontSize: 14, color: '#E5484D', fontWeight: 600 }}>
              Delete account
            </div>
            <div style={{ fontFamily: theme.fontMono, fontSize: 10, color: theme.muted, letterSpacing: 0.5, marginTop: 2, fontWeight: 600 }}>
              PERMANENTLY ERASE YOUR DATA
            </div>
          </div>
          <svg width="8" height="14" viewBox="0 0 8 14" fill="none">
            <path d="M1 1l6 6-6 6" stroke={theme.faint} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </button>
      </Group>

      {/* SUPPORT */}
      <Group label="SUPPORT">
        <Row
          icon={
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
              <circle cx="12" cy="12" r="9" stroke={theme.text} strokeWidth="2"/>
              <path d="M9.5 9a2.5 2.5 0 015 0c0 2-2.5 2-2.5 4M12 17v.5" stroke={theme.text} strokeWidth="2" strokeLinecap="round"/>
            </svg>
          }
          title="Help center"
          onClick={() => setSupportPanel('help')}
          right={
            <svg width="8" height="14" viewBox="0 0 8 14" fill="none">
              <path d="M1 1l6 6-6 6" stroke={theme.faint} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          }
        />
        <Row
          icon={
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
              <path d="M4 5h16v11h-9l-4 4v-4H4V5z" stroke={theme.text} strokeWidth="2" strokeLinejoin="round"/>
            </svg>
          }
          title="Contact us"
          sub="Avg reply: 4 hours"
          onClick={() => setSupportPanel('contact')}
          right={
            <svg width="8" height="14" viewBox="0 0 8 14" fill="none">
              <path d="M1 1l6 6-6 6" stroke={theme.faint} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          }
        />
        <Row
          icon={
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
              <path d="M12 2L2 7v6c0 5 4 8 10 9 6-1 10-4 10-9V7l-10-5z" stroke={theme.text} strokeWidth="2" strokeLinejoin="round"/>
            </svg>
          }
          title="Privacy & terms"
          onClick={() => setSupportPanel('privacy')}
          right={
            <svg width="8" height="14" viewBox="0 0 8 14" fill="none">
              <path d="M1 1l6 6-6 6" stroke={theme.faint} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          }
        />
      </Group>

      {/* COACH REVIEW QUEUE — gated to coach/admin (always on in demo mode) */}
      {onOpenCoachQueue && (
        <div style={{ padding: `${theme.gap + 4}px ${theme.pad}px 0` }}>
          <button onClick={onOpenCoachQueue} style={{
            width: '100%', padding: 0, border: 'none', cursor: 'pointer',
            borderRadius: 14, overflow: 'hidden', textAlign: 'left',
            background: 'transparent',
          }}>
            <div style={{
              position: 'relative', padding: 16,
              background: theme.accent, color: theme.onAccent,
              borderRadius: 14, overflow: 'hidden',
              display: 'flex', alignItems: 'center', gap: 12,
            }}>
              <div style={{
                width: 38, height: 38, borderRadius: 10,
                background: 'rgba(0,0,0,0.18)', color: theme.onAccent,
                display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
              }}>
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
                  <path d="M9 18V5l10-2v13" stroke={theme.onAccent} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                  <circle cx="6" cy="18" r="3" stroke={theme.onAccent} strokeWidth="2" />
                  <circle cx="16" cy="16" r="3" stroke={theme.onAccent} strokeWidth="2" />
                </svg>
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{
                  fontFamily: theme.fontMono, fontSize: 9, color: theme.onAccent, opacity: 0.8,
                  letterSpacing: 1, fontWeight: 700,
                }}>★ COACH</div>
                <div style={{
                  fontFamily: theme.fontDisplay, fontSize: 18, color: theme.onAccent,
                  letterSpacing: 0.3, lineHeight: 1, textTransform: 'uppercase', marginTop: 4,
                }}>REVIEW QUEUE</div>
                <div style={{
                  fontFamily: theme.fontMono, fontSize: 9, color: theme.onAccent, opacity: 0.7,
                  letterSpacing: 0.5, fontWeight: 600, marginTop: 4,
                }}>MEMBER SONG SUBMISSIONS · SCORE & SEND</div>
              </div>
              <span style={{
                fontFamily: theme.fontMono, fontSize: 11, color: theme.onAccent,
                letterSpacing: 1, fontWeight: 700,
              }}>OPEN →</span>
            </div>
          </button>
        </div>
      )}

      {/* ADMIN — gated */}
      {onOpenAdmin && (
        <div style={{ padding: `${theme.gap + 4}px ${theme.pad}px 0` }}>
          <button onClick={onOpenAdmin} style={{
            width: '100%', padding: 0, border: 'none', cursor: 'pointer',
            borderRadius: 14, overflow: 'hidden', textAlign: 'left',
            background: 'transparent', position: 'relative',
          }}>
            <div style={{
              position: 'relative', padding: 16,
              background: theme.text, color: theme.bg,
              borderRadius: 14, overflow: 'hidden',
            }}>
              <div style={{
                position: 'absolute', inset: 0,
                backgroundImage: 'url(assets/deep-field.png)',
                backgroundSize: 'cover', backgroundPosition: 'center',
                opacity: 0.18,
              }} />
              <div style={{ position: 'relative', display: 'flex', alignItems: 'center', gap: 12 }}>
                <div style={{
                  width: 38, height: 38, borderRadius: 10,
                  background: theme.accent, color: theme.onAccent,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  flexShrink: 0,
                }}>
                  <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
                    <path d="M3 13l2-6 7 4 7-4 2 6M5 7l7-4 7 4M3 13v6h18v-6" stroke={theme.onAccent} strokeWidth="2" strokeLinejoin="round" strokeLinecap="round"/>
                  </svg>
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{
                    fontFamily: theme.fontMono, fontSize: 9, color: theme.accent,
                    letterSpacing: 1, fontWeight: 700,
                  }}>★ LAUNCH HQ</div>
                  <div style={{
                    fontFamily: theme.fontDisplay, fontSize: 18, color: theme.bg,
                    letterSpacing: 0.3, lineHeight: 1, textTransform: 'uppercase', marginTop: 4,
                  }}>ADMIN DASHBOARD</div>
                  <div style={{
                    fontFamily: theme.fontMono, fontSize: 9, color: theme.bg, opacity: 0.5,
                    letterSpacing: 0.5, fontWeight: 600, marginTop: 4,
                  }}>INSIGHTS · TRANSACTIONS · PAYOUTS</div>
                </div>
                <span style={{
                  fontFamily: theme.fontMono, fontSize: 11, color: theme.accent,
                  letterSpacing: 1, fontWeight: 700,
                }}>OPEN →</span>
              </div>
            </div>
          </button>
        </div>
      )}

      {/* Version — five taps open the store diagnostics (see runStoreDiag). */}
      <div
        onClick={() => {
          const n = diagTaps + 1;
          if (n >= 5) { setDiagTaps(0); runStoreDiag(); } else setDiagTaps(n);
        }}
        style={{
          padding: `${theme.gap + 10}px ${theme.pad}px 0`, textAlign: 'center',
          cursor: 'default',
        }}>
        <div style={{
          fontFamily: theme.fontDisplay, fontSize: 14, color: theme.muted,
          letterSpacing: 2, textTransform: 'uppercase',
        }}>LAUNCH</div>
        <div style={{
          fontFamily: theme.fontMono, fontSize: 9, color: theme.faint,
          letterSpacing: 1, fontWeight: 600, marginTop: 4,
        }}>VERSION 1.0.0 · BUILD 2487 · MADE IN NASHVILLE</div>
      </div>

      {/* STORE DIAGNOSTICS — hidden panel, five taps on the version line.
          When in-app purchases come up unavailable on a device, the JS lives
          inside the binary and there's no console to read, so this is the only
          way to tell WHICH piece is missing: the native plugin, the RevenueCat
          key, or the products in App Store Connect. */}
      {storeDiag && (
        <div style={{
          position: 'fixed', inset: 0, zIndex: 90, background: 'rgba(0,0,0,0.92)',
          padding: 18, overflowY: 'auto', WebkitOverflowScrolling: 'touch',
        }}>
          <div style={{
            fontFamily: theme.fontDisplay, fontSize: 16, color: '#fff',
            letterSpacing: 1.5, textTransform: 'uppercase', marginBottom: 12,
          }}>Store diagnostics</div>
          <div style={{
            fontFamily: theme.fontMono, fontSize: 11, color: 'rgba(255,255,255,0.9)',
            whiteSpace: 'pre-wrap', lineHeight: 1.7, wordBreak: 'break-word',
          }}>{storeDiag}</div>
          <div style={{ display: 'flex', gap: 10, marginTop: 18 }}>
            <button onClick={runStoreTest} style={{
              flex: 1, padding: 12, borderRadius: 12, border: '1px solid rgba(255,255,255,0.25)',
              background: 'transparent', color: '#fff', fontFamily: theme.fontMono,
              fontSize: 11, letterSpacing: 1, fontWeight: 700,
            }}>TEST STORE</button>
            <button onClick={() => setStoreDiag(null)} style={{
              flex: 1, padding: 12, borderRadius: 12, border: 'none',
              background: theme.accent, color: '#fff', fontFamily: theme.fontMono,
              fontSize: 11, letterSpacing: 1, fontWeight: 700,
            }}>CLOSE</button>
          </div>
        </div>
      )}

      {/* SUPPORT OVERLAY — Help center / Contact us / Privacy & terms */}
      {supportPanel && (
        <SupportSheet
          theme={theme}
          panel={supportPanel}
          onClose={() => setSupportPanel(null)}
        />
      )}

      {/* DELETE ACCOUNT — warning → password → wipe from Supabase */}
      {showDelete && (
        <DeleteAccountSheet theme={theme} onClose={() => setShowDelete(false)} />
      )}
    </div>
  );
}

// ────────────────────────────────────────────────────────
// DeleteAccountSheet — irreversible account deletion flow.
//   step 'warn'     → explains the consequences, asks to confirm
//   step 'password' → final confirmation: re-enter the account password
// On success the account + all data are wiped from Supabase and the app is
// reloaded back to the login screen.
// ────────────────────────────────────────────────────────
const DANGER = '#E5484D';

function DeleteAccountSheet({ theme, onClose }) {
  const U = window.LAUNCH_USER;
  const [step, setStep] = useStateSet('warn');   // 'warn' | 'password'
  const [password, setPassword] = useStateSet('');
  const [confirmText, setConfirmText] = useStateSet(''); // for OAuth accounts (type DELETE)
  const [hasPassword, setHasPassword] = useStateSet(true); // email/pw account? (Google = false)
  const [busy, setBusy] = useStateSet(false);
  const [err, setErr] = useStateSet(null);

  // OAuth-only accounts (e.g. Google) have no password → confirm by typing DELETE.
  useEffectSet(() => {
    let alive = true;
    if (U && U.authProviders) {
      U.authProviders().then(a => { if (alive && a) setHasPassword(!!a.hasPassword); });
    }
    return () => { alive = false; };
  }, []);

  const canConfirm = hasPassword ? !!password : confirmText.trim().toUpperCase() === 'DELETE';

  const doDelete = async () => {
    if (!canConfirm) {
      setErr(hasPassword ? 'Enter your password to confirm.' : 'Type DELETE to confirm.');
      return;
    }
    setBusy(true); setErr(null);
    const res = U && U.deleteAccount ? await U.deleteAccount(hasPassword ? password : '') : { error: 'Unavailable.' };
    setBusy(false);
    if (res && res.ok) {
      // Account is gone — hard reload drops back to the welcome / login flow.
      try { window.location.reload(); } catch (e) { onClose(); }
    } else {
      setErr((res && res.error) || 'Could not delete your account.');
    }
  };

  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 80,
      background: theme.bg, display: 'flex', flexDirection: 'column',
    }}>
      {/* Top bar */}
      <div style={{
        paddingTop: 58, paddingBottom: 10, paddingLeft: theme.pad, paddingRight: theme.pad,
        display: 'flex', alignItems: 'center', gap: 12, flexShrink: 0,
      }}>
        <button onClick={onClose} style={{
          width: 38, height: 38, borderRadius: 12,
          background: theme.surface, border: `1px solid ${theme.border}`,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          cursor: 'pointer', padding: 0,
        }}>
          <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
            <path d="M2 2l10 10M12 2L2 12" stroke={theme.text} strokeWidth="2.2" strokeLinecap="round"/>
          </svg>
        </button>
        <div style={{ fontFamily: theme.fontMono, fontSize: 10, color: DANGER, letterSpacing: 1, fontWeight: 700 }}>
          {step === 'warn' ? 'DANGER ZONE' : 'FINAL CONFIRMATION'}
        </div>
      </div>

      <div style={{ flex: 1, overflowY: 'auto', padding: `10px ${theme.pad}px 0` }}>
        {/* Warning icon */}
        <div style={{
          width: 64, height: 64, borderRadius: 18, background: `${DANGER}22`,
          display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 16,
        }}>
          <svg width="30" height="30" viewBox="0 0 24 24" fill="none">
            <path d="M12 3L2 20h20L12 3z" stroke={DANGER} strokeWidth="2" strokeLinejoin="round"/>
            <path d="M12 10v4M12 17v.5" stroke={DANGER} strokeWidth="2" strokeLinecap="round"/>
          </svg>
        </div>

        <DisplayHeading theme={theme} size={30}>DELETE ACCOUNT</DisplayHeading>

        {step === 'warn' && (
          <>
            <div style={{ fontFamily: theme.fontBody, fontSize: 15, color: theme.text, lineHeight: 1.55, marginTop: 14, fontWeight: 600 }}>
              This will permanently delete your account.
            </div>
            <div style={{ fontFamily: theme.fontBody, fontSize: 14, color: theme.muted, lineHeight: 1.55, marginTop: 10 }}>
              All of your data will be erased from the app — your profile, songs, submissions,
              reviews, points and progress. <span style={{ color: DANGER, fontWeight: 700 }}>This action cannot be undone.</span>
            </div>
            <div style={{ fontFamily: theme.fontBody, fontSize: 14, color: theme.muted, lineHeight: 1.55, marginTop: 10 }}>
              Are you sure you want to continue?
            </div>
          </>
        )}

        {step === 'password' && (
          <>
            <div style={{ fontFamily: theme.fontBody, fontSize: 14, color: theme.muted, lineHeight: 1.55, marginTop: 14 }}>
              {hasPassword
                ? 'Enter your account password to permanently delete your account.'
                : 'Type DELETE to permanently delete your account.'}
            </div>
            <div style={{ marginTop: 16 }}>
              <label style={{
                fontFamily: theme.fontMono, fontSize: 10, color: theme.muted,
                letterSpacing: 1, fontWeight: 700, display: 'block', marginBottom: 8,
              }}>{hasPassword ? 'PASSWORD' : 'TYPE "DELETE"'}</label>
              <input
                type={hasPassword ? 'password' : 'text'}
                value={hasPassword ? password : confirmText}
                autoFocus
                onChange={(e) => { hasPassword ? setPassword(e.target.value) : setConfirmText(e.target.value); setErr(null); }}
                onKeyDown={(e) => { if (e.key === 'Enter' && !busy) doDelete(); }}
                placeholder={hasPassword ? 'Your password' : 'DELETE'}
                style={{
                  width: '100%', padding: '14px 16px', borderRadius: 12,
                  background: theme.surface, border: `1px solid ${err ? DANGER : theme.border}`,
                  color: theme.text, fontFamily: theme.fontBody, fontSize: 15, outline: 'none',
                }}
              />
            </div>
            {err && (
              <div style={{
                marginTop: 10, padding: '9px 12px', borderRadius: 10,
                background: `${DANGER}18`, border: `1px solid ${DANGER}55`,
                fontFamily: theme.fontBody, fontSize: 12, color: DANGER,
              }}>{err}</div>
            )}
          </>
        )}
      </div>

      {/* Sticky actions */}
      <div style={{
        padding: `12px ${theme.pad}px 28px`,
        borderTop: `1px solid ${theme.border}`, flexShrink: 0,
        display: 'flex', flexDirection: 'column', gap: 10,
      }}>
        {step === 'warn' ? (
          <>
            <button onClick={() => { setErr(null); setStep('password'); }} style={{
              width: '100%', padding: '15px 18px', borderRadius: 12, border: 'none',
              background: DANGER, color: '#fff',
              fontFamily: theme.fontDisplay, fontSize: 15, letterSpacing: 1,
              textTransform: 'uppercase', cursor: 'pointer',
            }}>Yes, delete my account</button>
            <button onClick={onClose} style={{
              width: '100%', padding: '14px 18px', borderRadius: 12,
              background: 'transparent', border: `1px solid ${theme.border}`, color: theme.text,
              fontFamily: theme.fontMono, fontSize: 12, letterSpacing: 1, fontWeight: 700,
              textTransform: 'uppercase', cursor: 'pointer',
            }}>Cancel</button>
          </>
        ) : (
          <>
            <button onClick={doDelete} disabled={busy || !canConfirm} style={{
              width: '100%', padding: '15px 18px', borderRadius: 12, border: 'none',
              background: (busy || !canConfirm) ? theme.surface2 : DANGER,
              color: (busy || !canConfirm) ? theme.faint : '#fff',
              fontFamily: theme.fontDisplay, fontSize: 15, letterSpacing: 1,
              textTransform: 'uppercase', cursor: (busy || !canConfirm) ? 'not-allowed' : 'pointer',
            }}>{busy ? 'DELETING…' : 'Delete my account permanently'}</button>
            <button onClick={() => { setStep('warn'); setErr(null); }} disabled={busy} style={{
              width: '100%', padding: '14px 18px', borderRadius: 12,
              background: 'transparent', border: `1px solid ${theme.border}`, color: theme.text,
              fontFamily: theme.fontMono, fontSize: 12, letterSpacing: 1, fontWeight: 700,
              textTransform: 'uppercase', cursor: busy ? 'not-allowed' : 'pointer',
            }}>Back</button>
          </>
        )}
      </div>
    </div>
  );
}

// ────────────────────────────────────────────────────────
// SupportSheet — full-screen overlay for the SUPPORT rows.
// Self-contained: no app wiring needed, opens over Settings.
// ────────────────────────────────────────────────────────
const SUPPORT_FAQ = [
  {
    q: 'How do my lessons and streak work?',
    a: 'Complete your daily lesson to keep your streak alive. Miss a day and the streak resets, but your total XP and progress are always saved.',
  },
  {
    q: 'How do I book a session with a coach?',
    a: 'Open your Profile, scroll to the coaches block, and tap Book a session. You can pick a time that matches the coach’s availability.',
  },
  {
    q: 'How do community points work?',
    a: 'You earn points from lessons, streaks and community activity. Redeem them for perks from the Feed tab. Some rewards may require an active subscription.',
  },
  {
    q: 'How do I change or cancel my subscription?',
    a: 'Go to Settings → Account → Subscription to switch plans. Your plan stays active until the end of the current billing period.',
  },
  {
    q: 'I found a bug or my screen is blank.',
    a: 'Try closing and reopening the app first. If it persists, use Contact us below and tell us what screen you were on — it helps us fix it fast.',
  },
];

function SupportSheet({ theme, panel, onClose }) {
  const titles = { help: 'Help center', contact: 'Contact us', privacy: 'Privacy & terms' };
  const [openFaq, setOpenFaq] = useStateSet(null);
  const [docView, setDocView] = useStateSet(null);   // legal doc open in the in-app reader (null = none)

  const Section = ({ children }) => (
    <Card theme={theme} style={{ overflow: 'hidden', marginTop: 14 }}>{children}</Card>
  );

  const Para = ({ children, mono }) => (
    <div style={{
      fontFamily: mono ? theme.fontMono : theme.fontBody,
      fontSize: mono ? 11 : 14, lineHeight: 1.55,
      color: theme.muted, padding: '14px 16px',
      letterSpacing: mono ? 0.4 : 0,
    }}>{children}</div>
  );

  const ContactRow = ({ label, value, href }) => (
    <a href={href} target="_blank" rel="noreferrer" style={{
      display: 'flex', alignItems: 'center', gap: 12, textDecoration: 'none',
      padding: '14px 16px',
    }}>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{
          fontFamily: theme.fontMono, fontSize: 10, color: theme.muted,
          letterSpacing: 1, fontWeight: 700,
        }}>{label}</div>
        <div style={{
          fontFamily: theme.fontBody, fontSize: 14, color: theme.text,
          fontWeight: 600, marginTop: 3,
        }}>{value}</div>
      </div>
      <svg width="8" height="14" viewBox="0 0 8 14" fill="none">
        <path d="M1 1l6 6-6 6" stroke={theme.faint} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
      </svg>
    </a>
  );

  return (
    <>
    <div style={{
      position: 'absolute', inset: 0, zIndex: 50,
      background: theme.bg, overflowY: 'auto',
      paddingBottom: 110,
    }}>
      {/* Top bar */}
      <div style={{
        paddingTop: 58, paddingBottom: 8, paddingLeft: theme.pad, paddingRight: theme.pad,
        display: 'flex', alignItems: 'center', gap: 12,
      }}>
        <button onClick={onClose} style={{
          width: 38, height: 38, borderRadius: 12,
          background: theme.surface, border: `1px solid ${theme.border}`,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          cursor: 'pointer',
        }}>
          <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
            <path d="M9 2L4 7l5 5" stroke={theme.text} strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </button>
      </div>

      <div style={{ padding: `4px ${theme.pad}px 0` }}>
        <div style={{ fontFamily: theme.fontMono, fontSize: 10, color: theme.muted, letterSpacing: 1, fontWeight: 700 }}>
          ★ SUPPORT
        </div>
        <DisplayHeading theme={theme} size={32}>{(titles[panel] || '').toUpperCase()}</DisplayHeading>
      </div>

      <div style={{ padding: `0 ${theme.pad}px` }}>
        {panel === 'help' && (
          <Section>
            {SUPPORT_FAQ.map((item, i) => {
              const open = openFaq === i;
              return (
                <React.Fragment key={i}>
                  {i > 0 && <div style={{ height: 1, background: theme.border }} />}
                  <button onClick={() => setOpenFaq(open ? null : i)} style={{
                    width: '100%', textAlign: 'left', background: 'transparent',
                    border: 'none', cursor: 'pointer', padding: '16px',
                    display: 'flex', flexDirection: 'column', gap: 8,
                  }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                      <div style={{
                        flex: 1, fontFamily: theme.fontBody, fontSize: 14,
                        color: theme.text, fontWeight: 600,
                      }}>{item.q}</div>
                      <span style={{
                        fontFamily: theme.fontMono, fontSize: 16, color: theme.muted,
                        transform: open ? 'rotate(45deg)' : 'none', transition: 'transform .15s',
                      }}>+</span>
                    </div>
                    {open && (
                      <div style={{
                        fontFamily: theme.fontBody, fontSize: 13, lineHeight: 1.55,
                        color: theme.muted,
                      }}>{item.a}</div>
                    )}
                  </button>
                </React.Fragment>
              );
            })}
          </Section>
        )}

        {panel === 'contact' && (
          <>
            <Para>Questions, feedback or trouble with the app? Reach the Launch team — we usually reply within 4 hours.</Para>
            <Section>
              <ContactRow label="EMAIL" value="support@launchnashville.com" href="mailto:support@launchnashville.com" />
              <div style={{ height: 1, background: theme.border }} />
              <ContactRow label="INSTAGRAM" value="@launchnash" href="https://www.instagram.com/launchnash/" />
            </Section>
          </>
        )}

        {panel === 'privacy' && (
          <>
            <Section>
              <Para mono>LAST UPDATED · JUNE 2026</Para>
            </Section>
            <Section>
              <Para>
                Launch collects only the information needed to run your account: your name, handle,
                email, lesson progress and the content you submit. We never sell your personal data.
              </Para>
            </Section>
            <Section>
              <Para>
                Your songs and submissions stay private to you and the coaches you share them with.
                Subscriptions renew automatically until cancelled and are governed by our standard
                Terms of Service. You can request deletion of your account and data at any time by
                contacting support.
              </Para>
            </Section>

            {/* Legal documents — open the full policies on launchnash.com (new tab). */}
            <div style={{ padding: '18px 4px 0', fontFamily: theme.fontMono, fontSize: 10, color: theme.muted, letterSpacing: 1, fontWeight: 700 }}>
              LEGAL DOCUMENTS
            </div>
            <Section>
              {[
                { title: 'Privacy Policy', href: 'https://www.launchnash.com/english-privacy-policy' },
                { title: 'Terms of Service', href: 'https://www.launchnash.com/terms-of-service' },
                { title: 'Community Guidelines', href: 'https://www.launchnash.com/community-guidelines' },
                { title: 'Copyright & DMCA Policy', href: 'https://www.launchnash.com/copyright-dmca-policy' },
                { title: 'Song Submission & Evaluation Agreement', href: 'documents/Song_Submission_Agreement_Launch.pdf' },
              ].map((doc, i) => (
                <React.Fragment key={doc.href}>
                  {i > 0 && <div style={{ height: 1, background: theme.border }} />}
                  <button onClick={() => setDocView(doc)} style={{
                    width: '100%', display: 'flex', alignItems: 'center', gap: 12,
                    background: 'transparent', border: 'none', cursor: 'pointer',
                    textAlign: 'left', padding: '15px 16px',
                  }}>
                    <div style={{
                      flex: 1, minWidth: 0, fontFamily: theme.fontBody, fontSize: 14,
                      color: theme.text, fontWeight: 600,
                    }}>{doc.title}</div>
                    <svg width="8" height="14" viewBox="0 0 8 14" fill="none">
                      <path d="M1 1l6 6-6 6" stroke={theme.faint} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
                    </svg>
                  </button>
                </React.Fragment>
              ))}
            </Section>

            <div style={{ padding: '14px 4px 0' }}>
              <a href="mailto:support@launchnashville.com" style={{
                fontFamily: theme.fontMono, fontSize: 11, color: theme.accent,
                letterSpacing: 0.5, fontWeight: 700, textDecoration: 'none',
              }}>REQUEST DATA DELETION →</a>
            </div>
          </>
        )}
      </div>
    </div>

    {/* In-app legal document reader — read the policy inside the app, then continue. */}
    {docView && (
      <div style={{
        position: 'absolute', inset: 0, zIndex: 70,
        background: theme.bg, display: 'flex', flexDirection: 'column',
      }}>
        {/* Top bar: back · title · open-in-browser fallback */}
        <div style={{
          paddingTop: 58, paddingBottom: 10, paddingLeft: theme.pad, paddingRight: theme.pad,
          display: 'flex', alignItems: 'center', gap: 10,
          borderBottom: `1px solid ${theme.border}`, flexShrink: 0,
        }}>
          <button onClick={() => setDocView(null)} style={{
            width: 38, height: 38, borderRadius: 12,
            background: theme.surface, border: `1px solid ${theme.border}`,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            cursor: 'pointer', flexShrink: 0, padding: 0,
          }}>
            <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
              <path d="M9 2L4 7l5 5" stroke={theme.text} strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </button>
          <div style={{
            flex: 1, minWidth: 0, textAlign: 'center',
            fontFamily: theme.fontMono, fontSize: 11, color: theme.text,
            letterSpacing: 1, fontWeight: 700,
            overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
          }}>{docView.title.toUpperCase()}</div>
          <a href={docView.href} target="_blank" rel="noreferrer" title="Open in browser" style={{
            width: 38, height: 38, borderRadius: 12,
            background: theme.surface, border: `1px solid ${theme.border}`,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            cursor: 'pointer', flexShrink: 0, textDecoration: 'none',
          }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none">
              <path d="M7 17L17 7M17 7H9M17 7v8" stroke={theme.text} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </a>
        </div>

        {/* Document (embedded page) */}
        <div style={{ flex: 1, minHeight: 0, background: '#fff', position: 'relative' }}>
          <div style={{
            position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontFamily: theme.fontMono, fontSize: 11, color: '#888', letterSpacing: 0.5,
          }}>Loading…</div>
          <iframe
            title={docView.title}
            src={docView.href}
            style={{ position: 'relative', width: '100%', height: '100%', border: 'none' }}
          />
        </div>

        {/* Continue back into the app */}
        <div style={{
          padding: `12px ${theme.pad}px 28px`,
          borderTop: `1px solid ${theme.border}`, flexShrink: 0,
        }}>
          <button onClick={() => setDocView(null)} style={{
            width: '100%', padding: '15px 18px', borderRadius: 12, border: 'none',
            background: theme.accent, color: theme.onAccent,
            fontFamily: theme.fontDisplay, fontSize: 15, letterSpacing: 1,
            textTransform: 'uppercase', cursor: 'pointer',
          }}>✓ Done — Back to app</button>
        </div>
      </div>
    )}
    </>
  );
}

// ────────────────────────────────────────────────────────
// EditProfileScreen — edit display name, handle & bio.
// Reached from Settings → Account → Edit profile. Persists via
// window.LAUNCH_USER.saveProfile so the name shown across the app updates.
// ────────────────────────────────────────────────────────
const AVATAR_COLORS = ['#C72820', '#7A5AE0', '#CAFF33', '#FBBF24', '#22C55E', '#EC4899', '#06B6D4', '#F97316'];

function EditProfileScreen({ theme, onBack }) {
  const user = window.LAUNCH_USER.useUser();
  const [name, setName] = useStateSet(user.displayName || '');
  const [handle, setHandle] = useStateSet(user.handle || '');
  const [bio, setBio] = useStateSet(user.bio || '');
  const [color, setColor] = useStateSet(user.color || AVATAR_COLORS[0]);
  const [saving, setSaving] = useStateSet(false);

  const initials = window.LAUNCH_USER.initialsFrom(name, handle);

  const save = async () => {
    setSaving(true);
    try {
      await window.LAUNCH_USER.saveProfile({
        displayName: name.trim(),
        handle: handle.trim().toLowerCase().replace(/[^a-z0-9._]/g, ''),
        bio: bio.trim(),
        color,
      });
    } catch (e) { /* saveProfile already falls back to local cache */ }
    setSaving(false);
    onBack && onBack();
  };

  const Label = ({ children }) => (
    <div style={{
      fontFamily: theme.fontMono, fontSize: 10, color: theme.muted,
      letterSpacing: 1, fontWeight: 700, marginBottom: 8, marginTop: 18,
    }}>{children}</div>
  );
  const inputStyle = {
    width: '100%', boxSizing: 'border-box',
    padding: '14px', borderRadius: 12,
    border: `1px solid ${theme.border}`,
    fontFamily: theme.fontBody, fontSize: 15,
  };

  return (
    <div style={{ paddingBottom: 130 }}>
      {/* Top bar */}
      <div style={{
        paddingTop: 58, paddingBottom: 8, paddingLeft: theme.pad, paddingRight: theme.pad,
        display: 'flex', alignItems: 'center', gap: 12,
      }}>
        <button onClick={onBack} style={{
          width: 38, height: 38, borderRadius: 12,
          background: theme.surface, border: `1px solid ${theme.border}`,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          cursor: 'pointer',
        }}>
          <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
            <path d="M9 2L4 7l5 5" stroke={theme.text} strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </button>
      </div>

      <div style={{ padding: `4px ${theme.pad}px 0` }}>
        <div style={{ fontFamily: theme.fontMono, fontSize: 10, color: theme.muted, letterSpacing: 1, fontWeight: 700 }}>
          ★ YOUR IDENTITY
        </div>
        <DisplayHeading theme={theme} size={36}>EDIT PROFILE</DisplayHeading>
      </div>

      <div style={{ padding: `8px ${theme.pad}px 0` }}>
        {/* Avatar preview + color picker */}
        <Label>AVATAR</Label>
        <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
          <div style={{
            width: 64, height: 64, borderRadius: '50%', flexShrink: 0,
            background: color, color: '#0A0A0A',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontFamily: theme.fontDisplay, fontSize: 24, letterSpacing: 0.5,
          }}>{initials}</div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 10, flex: 1 }}>
            {AVATAR_COLORS.map(c => (
              <button key={c} onClick={() => setColor(c)} aria-label={c} style={{
                width: 30, height: 30, borderRadius: '50%', background: c,
                border: 'none', cursor: 'pointer', padding: 0,
                boxShadow: color === c
                  ? `0 0 0 2px ${theme.bg}, 0 0 0 4px ${c}`
                  : `0 0 0 1px ${theme.border}`,
              }} />
            ))}
          </div>
        </div>

        <Label>DISPLAY NAME</Label>
        <input value={name} onChange={(e) => setName(e.target.value)}
          placeholder="Your name" style={inputStyle} />

        <Label>HANDLE</Label>
        <input value={handle} onChange={(e) => setHandle(e.target.value)}
          placeholder="your.handle" style={inputStyle} />

        <Label>BIO</Label>
        <textarea value={bio} onChange={(e) => setBio(e.target.value)}
          placeholder="A line or two about your sound"
          rows={3} style={{ ...inputStyle, resize: 'vertical' }} />

        <button onClick={save} disabled={saving} style={{
          width: '100%', marginTop: 24,
          background: theme.accent, color: theme.onAccent,
          border: 'none', borderRadius: 14,
          fontFamily: theme.fontDisplay, fontSize: 16, letterSpacing: 1,
          padding: '18px', cursor: saving ? 'default' : 'pointer',
          textTransform: 'uppercase', opacity: saving ? 0.6 : 1,
        }}>{saving ? 'SAVING…' : 'SAVE CHANGES'}</button>
      </div>
    </div>
  );
}

window.LAUNCH_SCREENS_8 = { SettingsScreen, EditProfileScreen };
