// create.jsx — Create tab: Weekly Songwriting Challenge + Daily Prompt Generator
// Submissions persist to localStorage so artists keep a writing log.

const { useState: useStateC, useEffect: useEffectC, useRef: useRefC } = React;
const { Card, Chip, TopBar, IconBtn, DisplayHeading, Icon } = window.LAUNCH_SCREENS_1;

// ────────────────────────────────────────────────────────
// Data — challenge & prompt bank
// ────────────────────────────────────────────────────────
const WEEKLY_CHALLENGE = {
  id: 'w19-2026',
  week: 'WEEK 19 · MAY 11 — 17',
  title: 'WRITE A CHORUS USING ONLY CONVERSATIONAL LANGUAGE',
  brief:
    'No metaphors. No big words. Write a chorus that sounds like something you\'d actually say to a friend at 2am. Real. Honest. Plain. The hook should feel like a sentence you didn\'t mean to start writing.',
  deadline: 'SUN · 11:59 PM ET',
  daysLeft: 3,
  prize: "TOP 3 GET A FREE IN-DEPTH EVAL + FEATURED IN NEXT WEEK'S DROPS",
  entries: 487,
};

const PROMPTS = [
  'Write from the perspective of regret.',
  'Describe a memory using only visuals.',
  'Write a hook under 8 words.',
  'Open with a question. End with the same question.',
  'Write a verse without using the word "I".',
  'Make a chorus out of what you almost texted.',
  'Tell the same story twice — verse one is the lie, verse two is the truth.',
  'Pick a city. Write about leaving it.',
  'Use a weather word as the title.',
  'Write a love song without saying love.',
  'Make the bridge the most honest part.',
  'Start the song mid-sentence.',
  'Write a chorus a 7-year-old could sing.',
  'Use only one-syllable words for the first verse.',
  'Build the whole song around a single noun.',
  'Replace every "you" with a name.',
  'Write to someone you haven\'t spoken to in years.',
  'Make the title the worst line in the song.',
  'Start in a kitchen. End in a car.',
  'Write a song that has to be sung at 4am.',
  'Use a question your mom used to ask.',
  'Write the verse you\'d never play for your dad.',
  'Open with a list. End with a refusal.',
  'Make the chorus a confession.',
  'Pick a song you hate. Steal its structure.',
  'Write a song that fits inside one room.',
];

// Sample community entries — what other artists submitted this week
const COMMUNITY_ENTRIES = [
  {
    handle: 'sasha.vee', lbl: 'SV', color: '#CAFF33',
    title: 'just don\'t go yet',
    snippet: '"just don\'t go yet / i made coffee / i know it\'s late / but the rain hasn\'t / i made coffee / just don\'t go yet"',
    likes: 142, comments: 23, fav: true,
  },
  {
    handle: 'kai.park', lbl: 'KP', color: '#C72820',
    title: 'so what now',
    snippet: '"so what now / you got the keys / you got the car / you got the better half of me / so what now"',
    likes: 89, comments: 14,
  },
  {
    handle: 'theo.m', lbl: 'TM', color: '#7A5AE0',
    title: 'tell me you mean it',
    snippet: '"tell me you mean it / look at me when you say it / i\'ll believe you / i swear i\'ll believe you / just tell me you mean it"',
    likes: 67, comments: 19,
  },
];

// ────────────────────────────────────────────────────────
// Storage — submissions log lives in localStorage
// Key: 'launch.submissions' = [{ id, kind, title, text, prompt, ts, week }]
// ────────────────────────────────────────────────────────
function loadSubmissions() {
  try {
    const raw = localStorage.getItem('launch.submissions');
    if (!raw) return [];
    return JSON.parse(raw);
  } catch (e) { return []; }
}
function saveSubmissions(list) {
  try { localStorage.setItem('launch.submissions', JSON.stringify(list)); } catch (e) {}
}
function fmtDate(ts) {
  const d = new Date(ts);
  const today = new Date();
  const isToday = d.toDateString() === today.toDateString();
  if (isToday) return 'TODAY · ' + d.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' }).toUpperCase();
  const yesterday = new Date(); yesterday.setDate(yesterday.getDate() - 1);
  if (d.toDateString() === yesterday.toDateString()) return 'YESTERDAY';
  return d.toLocaleDateString([], { month: 'short', day: 'numeric' }).toUpperCase();
}

// ────────────────────────────────────────────────────────
// Submission composer modal — for both weekly and daily
// ────────────────────────────────────────────────────────
function ComposerSheet({ theme, kind, prompt, onClose, onSubmit }) {
  const [title, setTitle] = useStateC('');
  const [text, setText] = useStateC('');
  const taRef = useRefC(null);

  useEffectC(() => {
    // small focus delay so the sheet has rendered
    const t = setTimeout(() => { if (taRef.current) taRef.current.focus(); }, 150);
    return () => clearTimeout(t);
  }, []);

  const canSubmit = text.trim().length > 0;

  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 100,
      background: 'rgba(0,0,0,0.6)', backdropFilter: 'blur(8px)',
      display: 'flex', alignItems: 'flex-end',
    }}>
      <div style={{
        width: '100%', background: theme.bg,
        borderRadius: '24px 24px 0 0',
        maxHeight: '92%', display: 'flex', flexDirection: 'column',
        animation: 'sheetUp .25s cubic-bezier(.2,.8,.2,1)',
      }}>
        <style>{`@keyframes sheetUp { from { transform: translateY(100%); } to { transform: translateY(0); } }`}</style>

        {/* handle */}
        <div style={{
          width: 40, height: 4, borderRadius: 99, background: theme.faint,
          margin: '10px auto 0', flexShrink: 0,
        }} />

        {/* head */}
        <div style={{ padding: `12px ${theme.pad}px 4px` }}>
          <div style={{
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            marginBottom: 10,
          }}>
            <div style={{
              fontFamily: theme.fontMono, fontSize: 10, color: theme.accent,
              letterSpacing: 1, fontWeight: 700,
            }}>★ {kind === 'weekly' ? 'WEEKLY CHALLENGE' : 'DAILY PROMPT'}</div>
            <button onClick={onClose} style={{
              width: 28, height: 28, borderRadius: 99, padding: 0,
              background: theme.surface, border: `1px solid ${theme.border}`,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              cursor: 'pointer',
            }}>
              <svg width="10" height="10" viewBox="0 0 14 14" fill="none">
                <path d="M2 2l10 10M12 2L2 12" stroke={theme.text} strokeWidth="2" strokeLinecap="round"/>
              </svg>
            </button>
          </div>
          <DisplayHeading theme={theme} size={20} style={{ lineHeight: 1 }}>
            {prompt}
          </DisplayHeading>
        </div>

        {/* form */}
        <div style={{
          flex: 1, overflowY: 'auto', padding: `${theme.gap}px ${theme.pad}px 0`,
          display: 'flex', flexDirection: 'column', gap: 12,
        }} className="launch-scroll">
          <input
            value={title}
            onChange={e => setTitle(e.target.value)}
            placeholder="Title (optional)"
            style={{
              width: '100%', padding: '12px 14px', borderRadius: 12,
              background: theme.surface, border: `1px solid ${theme.border}`,
              color: theme.text, fontFamily: theme.fontDisplay, fontSize: 20,
              outline: 'none', letterSpacing: 0.3, textTransform: 'uppercase',
            }}
          />
          <textarea
            ref={taRef}
            value={text}
            onChange={e => setText(e.target.value)}
            placeholder={"Start writing…\n\nLines, verse, chorus, scribbles — whatever you got. You can always edit later."}
            rows={10}
            style={{
              width: '100%', padding: '14px 16px', borderRadius: 12,
              background: theme.surface, border: `1px solid ${theme.border}`,
              color: theme.text, fontFamily: theme.fontBody, fontSize: 15,
              outline: 'none', resize: 'none', lineHeight: 1.55, minHeight: 200,
            }}
          />
          <div style={{
            fontFamily: theme.fontMono, fontSize: 10, color: theme.muted,
            letterSpacing: 0.5, fontWeight: 600, textAlign: 'right',
          }}>
            {text.trim().split(/\s+/).filter(Boolean).length} WORDS · {text.length} CHARS
          </div>
        </div>

        {/* submit bar */}
        <div style={{
          padding: `12px ${theme.pad}px 28px`,
          borderTop: `1px solid ${theme.border}`,
          background: theme.bg,
          display: 'flex', alignItems: 'center', gap: 10,
        }}>
          <button onClick={onClose} style={{
            padding: '12px 16px', borderRadius: 12,
            background: 'transparent', border: `1px solid ${theme.border}`,
            color: theme.text, fontFamily: theme.fontMono, fontSize: 11, fontWeight: 700,
            letterSpacing: 1, cursor: 'pointer', textTransform: 'uppercase',
          }}>SAVE DRAFT</button>
          <button
            onClick={() => canSubmit && onSubmit({ title: title.trim() || 'UNTITLED', text: text.trim(), prompt })}
            disabled={!canSubmit}
            style={{
              flex: 1, padding: '14px 18px', borderRadius: 12,
              background: canSubmit ? theme.accent : theme.surface2,
              color: canSubmit ? theme.onAccent : theme.faint,
              border: 'none', cursor: canSubmit ? 'pointer' : 'not-allowed',
              fontFamily: theme.fontDisplay, fontSize: 15, letterSpacing: 1,
              textTransform: 'uppercase',
            }}>
            {kind === 'weekly' ? 'SUBMIT ENTRY ↗' : 'LOG TO JOURNAL ↗'}
          </button>
        </div>
      </div>
    </div>
  );
}

// ────────────────────────────────────────────────────────
// Community entries panel
// ────────────────────────────────────────────────────────
function CommunityPanel({ theme, onClose }) {
  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 100,
      background: theme.bg, display: 'flex', flexDirection: 'column',
      animation: 'sheetUp .22s cubic-bezier(.2,.8,.2,1)',
    }}>
      {/* top */}
      <div style={{
        paddingTop: 58, paddingBottom: 8, paddingLeft: theme.pad, paddingRight: theme.pad,
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        borderBottom: `1px solid ${theme.border}`,
      }}>
        <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: theme.muted,
          letterSpacing: 1, fontWeight: 700,
        }}>{WEEKLY_CHALLENGE.entries} ENTRIES</div>
      </div>

      <div style={{ overflowY: 'auto', flex: 1, paddingBottom: 30 }} className="launch-scroll">
        <div style={{ padding: `${theme.gap}px ${theme.pad}px 0` }}>
          <div style={{
            fontFamily: theme.fontMono, fontSize: 10, color: theme.accent,
            letterSpacing: 1, fontWeight: 700,
          }}>★ COMMUNITY ENTRIES</div>
          <DisplayHeading theme={theme} size={32} style={{ marginTop: 6 }}>
            HOW THE SQUAD<br/>WROTE IT
          </DisplayHeading>
          <div style={{
            fontFamily: theme.fontBody, fontSize: 13, color: theme.muted,
            marginTop: 8, lineHeight: 1.5,
          }}>
            Sorted by hearts. Read 'em. Steal a line if you want — they put it out there.
          </div>
        </div>

        <div style={{ padding: `${theme.gap + 4}px ${theme.pad}px 0`, display: 'flex', flexDirection: 'column', gap: 10 }}>
          {COMMUNITY_ENTRIES.map((e, i) => (
            <Card key={i} theme={theme} style={{
              padding: 14,
              borderColor: e.fav ? theme.accent : theme.border,
            }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 }}>
                <div style={{
                  width: 32, height: 32, borderRadius: 99, background: e.color,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontFamily: theme.fontDisplay, color: '#0A0A0A', fontSize: 12,
                }}>{e.lbl}</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontFamily: theme.fontBody, fontSize: 14, color: theme.text, fontWeight: 600 }}>
                    {e.handle}
                  </div>
                  <div style={{ fontFamily: theme.fontMono, fontSize: 10, color: theme.muted, letterSpacing: 0.5 }}>
                    {e.title.toUpperCase()}
                  </div>
                </div>
                {e.fav && <Chip theme={theme} accent>★ PINNED</Chip>}
              </div>
              <div style={{
                fontFamily: theme.fontBody, fontSize: 14, color: theme.text,
                lineHeight: 1.55, fontStyle: 'italic',
                paddingLeft: 12, borderLeft: `2px solid ${theme.accent}`,
              }}>{e.snippet}</div>
              <div style={{
                display: 'flex', gap: 18, alignItems: 'center', marginTop: 10,
                paddingTop: 10, borderTop: `1px solid ${theme.border}`,
              }}>
                <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, color: theme.accent, fontFamily: theme.fontMono, fontSize: 11, fontWeight: 700 }}>
                  ♥ {e.likes}
                </span>
                <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, color: theme.muted, fontFamily: theme.fontMono, fontSize: 11, fontWeight: 700 }}>
                  💬 {e.comments}
                </span>
              </div>
            </Card>
          ))}
        </div>
      </div>
    </div>
  );
}

// ────────────────────────────────────────────────────────
// CreateScreen — the Create tab
// ────────────────────────────────────────────────────────
function CreateScreen({ theme, copy }) {
  // Daily prompt rotates through the bank. Start at a stable per-day index
  // so a given day still feels "today's prompt" rather than purely random.
  const today = new Date();
  const dayKey = `${today.getFullYear()}-${today.getMonth()}-${today.getDate()}`;
  const seedFor = (k) => {
    let h = 0; for (let i = 0; i < k.length; i++) h = ((h << 5) - h + k.charCodeAt(i)) | 0;
    return Math.abs(h);
  };
  const [promptIdx, setPromptIdx] = useStateC(() => seedFor(dayKey) % PROMPTS.length);
  const [composer, setComposer] = useStateC(null); // null | 'weekly' | 'daily'
  const [community, setCommunity] = useStateC(false);
  const [submissions, setSubmissions] = useStateC(() => loadSubmissions());
  const [rerollSpin, setRerollSpin] = useStateC(false);
  const [toast, setToast] = useStateC(null);

  const cyclePrompt = () => {
    setRerollSpin(true);
    setPromptIdx(i => (i + 1 + Math.floor(Math.random() * 3)) % PROMPTS.length);
    setTimeout(() => setRerollSpin(false), 400);
  };

  const submit = (entry) => {
    const newSub = {
      id: 's-' + Date.now(),
      kind: composer,
      ...entry,
      ts: Date.now(),
      week: WEEKLY_CHALLENGE.week,
    };
    const next = [newSub, ...submissions];
    setSubmissions(next);
    saveSubmissions(next);
    setComposer(null);
    setToast(composer === 'weekly' ? 'ENTRY SUBMITTED · +250 XP' : 'LOGGED TO JOURNAL · +30 XP');
    setTimeout(() => setToast(null), 2400);
  };

  const removeSub = (id) => {
    const next = submissions.filter(s => s.id !== id);
    setSubmissions(next);
    saveSubmissions(next);
  };

  const weeklySubs = submissions.filter(s => s.kind === 'weekly');
  const dailySubs = submissions.filter(s => s.kind === 'daily');

  return (
    <div style={{ paddingBottom: 110, position: 'relative' }}>
      <TopBar theme={theme}
        left={
          <div>
            <div style={{ fontFamily: theme.fontMono, fontSize: 10, color: theme.muted, letterSpacing: 1, fontWeight: 600 }}>
              ★ THE WORKBENCH
            </div>
            <DisplayHeading theme={theme} size={32} style={{ marginTop: 4 }}>
              CREATE
            </DisplayHeading>
          </div>
        }
        right={
          <div style={{
            padding: '8px 12px', borderRadius: 99,
            background: theme.surface, border: `1px solid ${theme.border}`,
            fontFamily: theme.fontMono, fontSize: 10, color: theme.accent,
            letterSpacing: 1, fontWeight: 700,
          }}>{submissions.length} LOGGED</div>
        }
      />

      {/* ░░ WEEKLY CHALLENGE — big featured card */}
      <div style={{ padding: `${theme.gap}px ${theme.pad}px 0` }}>
        <Card theme={theme} style={{
          padding: 0, overflow: 'hidden', position: 'relative',
          background: '#0A0A0A',
          borderColor: theme.accent,
          color: '#fff',
        }}>
          {/* JWST deep field backdrop */}
          <div style={{
            position: 'absolute', inset: 0,
            backgroundImage: 'url(assets/deep-field.png)',
            backgroundSize: 'cover', backgroundPosition: 'center',
            opacity: 0.55,
          }} />
          <div style={{
            position: 'absolute', inset: 0,
            background: `linear-gradient(160deg, ${theme.accent}66 0%, rgba(10,10,10,0.4) 50%, rgba(10,10,10,0.95) 100%)`,
          }} />

          <div style={{ position: 'relative', padding: 18 }}>
            {/* badge */}
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
              <div style={{
                padding: '5px 10px', borderRadius: 99, background: theme.accent,
                color: theme.onAccent, fontFamily: theme.fontMono, fontSize: 9, fontWeight: 700,
                letterSpacing: 1,
              }}>★ THIS WEEK'S CHALLENGE</div>
              <div style={{
                fontFamily: theme.fontMono, fontSize: 9, color: 'rgba(255,255,255,0.5)',
                letterSpacing: 1, fontWeight: 700,
              }}>{WEEKLY_CHALLENGE.week}</div>
            </div>

            {/* prompt */}
            <div style={{
              fontFamily: theme.fontDisplay, fontSize: 28, color: '#fff',
              lineHeight: 0.95, letterSpacing: 0.3, textTransform: 'uppercase',
              marginBottom: 14,
            }}>"{WEEKLY_CHALLENGE.title}"</div>

            {/* brief */}
            <div style={{
              fontFamily: theme.fontBody, fontSize: 13, color: 'rgba(255,255,255,0.75)',
              lineHeight: 1.55, marginBottom: 14,
            }}>{WEEKLY_CHALLENGE.brief}</div>

            {/* meta row */}
            <div style={{
              display: 'flex', alignItems: 'center', gap: 12,
              padding: '10px 12px', borderRadius: 10,
              background: 'rgba(0,0,0,0.45)', border: '1px solid rgba(255,255,255,0.12)',
              marginBottom: 14,
            }}>
              <div style={{ flex: 1 }}>
                <div style={{
                  fontFamily: theme.fontMono, fontSize: 9, color: 'rgba(255,255,255,0.5)',
                  letterSpacing: 1, fontWeight: 700,
                }}>DEADLINE · {WEEKLY_CHALLENGE.deadline}</div>
                <div style={{
                  fontFamily: theme.fontDisplay, fontSize: 22, color: theme.accent,
                  lineHeight: 1, letterSpacing: -0.2, marginTop: 4,
                }}>
                  {WEEKLY_CHALLENGE.daysLeft} <span style={{ color: '#fff', fontSize: 14, opacity: 0.8 }}>DAYS LEFT</span>
                </div>
              </div>
              <div style={{ textAlign: 'right' }}>
                <div style={{
                  fontFamily: theme.fontMono, fontSize: 9, color: 'rgba(255,255,255,0.5)',
                  letterSpacing: 1, fontWeight: 700,
                }}>ENTRIES</div>
                <div style={{
                  fontFamily: theme.fontDisplay, fontSize: 22, color: '#fff',
                  lineHeight: 1, letterSpacing: -0.2, marginTop: 4,
                }}>{WEEKLY_CHALLENGE.entries}</div>
              </div>
            </div>

            {/* buttons */}
            <div style={{ display: 'flex', gap: 8 }}>
              <button onClick={() => setComposer('weekly')} style={{
                flex: 1, padding: '14px', borderRadius: 12,
                background: theme.accent, color: theme.onAccent, border: 'none',
                fontFamily: theme.fontDisplay, fontSize: 14, letterSpacing: 1,
                cursor: 'pointer', textTransform: 'uppercase',
              }}>SUBMIT ENTRY ↗</button>
              <button onClick={() => setCommunity(true)} style={{
                flex: 1, padding: '14px', borderRadius: 12,
                background: 'rgba(255,255,255,0.1)', color: '#fff',
                border: '1px solid rgba(255,255,255,0.2)',
                fontFamily: theme.fontDisplay, fontSize: 14, letterSpacing: 1,
                cursor: 'pointer', textTransform: 'uppercase',
              }}>VIEW ENTRIES</button>
            </div>

            {/* prize line */}
            <div style={{
              marginTop: 12, padding: '8px 12px', borderRadius: 8,
              background: `${theme.accent}25`, border: `1px solid ${theme.accent}50`,
              fontFamily: theme.fontMono, fontSize: 10, color: theme.accent,
              letterSpacing: 0.8, fontWeight: 700, textAlign: 'center',
            }}>🏆 {WEEKLY_CHALLENGE.prize}</div>
          </div>
        </Card>
      </div>

      {/* ░░ DAILY PROMPT GENERATOR */}
      <div style={{ padding: `${theme.gap + 6}px ${theme.pad}px 0` }}>
        <div style={{
          fontFamily: theme.fontMono, fontSize: 11, color: theme.muted,
          letterSpacing: 1, fontWeight: 600, marginBottom: 10,
        }}>DAILY PROMPT · INFINITE REPLAY</div>
        <Card theme={theme} style={{ padding: 16, position: 'relative', overflow: 'hidden' }}>
          {/* subtle starfield */}
          <svg viewBox="0 0 100 100" preserveAspectRatio="none" style={{
            position: 'absolute', inset: 0, opacity: 0.15, pointerEvents: 'none',
          }}>
            {Array.from({ length: 20 }, (_, i) => {
              const x = (i * 17 + (promptIdx * 13)) % 100;
              const y = (i * 23 + (promptIdx * 7)) % 100;
              const r = (i % 4 === 0) ? 0.8 : 0.4;
              return <circle key={i} cx={x} cy={y} r={r} fill={theme.text}/>;
            })}
          </svg>

          <div style={{ position: 'relative' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}>
              <span style={{ fontSize: 16 }}>🎲</span>
              <span style={{
                fontFamily: theme.fontMono, fontSize: 10, color: theme.accent,
                letterSpacing: 1.5, fontWeight: 700,
              }}>PROMPT #{(promptIdx + 1).toString().padStart(3, '0')} · TODAY</span>
            </div>
            <div style={{
              fontFamily: theme.fontDisplay, fontSize: 26, color: theme.text,
              lineHeight: 1.05, letterSpacing: 0.2, textTransform: 'uppercase',
              minHeight: 80,
              opacity: rerollSpin ? 0.3 : 1,
              transition: 'opacity .2s',
            }}>"{PROMPTS[promptIdx]}"</div>
            <div style={{ display: 'flex', gap: 8, marginTop: 16 }}>
              <button onClick={() => setComposer('daily')} style={{
                flex: 2, padding: '13px', borderRadius: 12,
                background: theme.text, color: theme.bg, border: 'none',
                fontFamily: theme.fontDisplay, fontSize: 14, letterSpacing: 1,
                cursor: 'pointer', textTransform: 'uppercase',
              }}>WRITE IT ↗</button>
              <button onClick={cyclePrompt} style={{
                flex: 1, padding: '13px', borderRadius: 12,
                background: 'transparent', color: theme.text,
                border: `1px solid ${theme.border}`,
                fontFamily: theme.fontDisplay, fontSize: 14, letterSpacing: 1,
                cursor: 'pointer', textTransform: 'uppercase',
                display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
              }}>
                <span style={{
                  display: 'inline-block',
                  transform: rerollSpin ? 'rotate(360deg)' : 'rotate(0deg)',
                  transition: 'transform .4s ease',
                }}>↻</span>
                REROLL
              </button>
            </div>
          </div>
        </Card>
      </div>

      {/* ░░ MY WORKBENCH — submission log */}
      <div style={{ padding: `${theme.gap + 6}px ${theme.pad}px 0` }}>
        <div style={{
          display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
          marginBottom: 10,
        }}>
          <span style={{
            fontFamily: theme.fontMono, fontSize: 11, color: theme.muted,
            letterSpacing: 1, fontWeight: 600,
          }}>YOUR WORKBENCH · {submissions.length}</span>
          {submissions.length > 0 && (
            <span style={{
              fontFamily: theme.fontMono, fontSize: 10, color: theme.accent,
              letterSpacing: 0.5, fontWeight: 700,
            }}>SAVED LOCALLY ✓</span>
          )}
        </div>

        {submissions.length === 0 ? (
          <Card theme={theme} style={{
            padding: 24, textAlign: 'center',
            borderStyle: 'dashed', borderColor: theme.border,
          }}>
            <div style={{ fontSize: 32, marginBottom: 8 }}>✍︎</div>
            <div style={{
              fontFamily: theme.fontDisplay, fontSize: 18, color: theme.text,
              letterSpacing: 0.3, textTransform: 'uppercase',
            }}>NOTHING WRITTEN YET</div>
            <div style={{
              fontFamily: theme.fontBody, fontSize: 13, color: theme.muted,
              marginTop: 6, lineHeight: 1.45,
            }}>
              Tap a prompt above. Every entry saves to your workbench so you can come back to it.
            </div>
          </Card>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {submissions.map(s => (
              <Card key={s.id} theme={theme} style={{ padding: 14, position: 'relative' }}>
                <div style={{
                  display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                  marginBottom: 8, gap: 8,
                }}>
                  <Chip theme={theme} accent={s.kind === 'weekly'}>
                    {s.kind === 'weekly' ? '★ WEEKLY ENTRY' : 'DAILY · LOG'}
                  </Chip>
                  <span style={{
                    fontFamily: theme.fontMono, fontSize: 9, color: theme.muted,
                    letterSpacing: 0.8, fontWeight: 700,
                  }}>{fmtDate(s.ts)}</span>
                </div>
                <div style={{
                  fontFamily: theme.fontDisplay, fontSize: 18, color: theme.text,
                  letterSpacing: 0.2, lineHeight: 1, textTransform: 'uppercase',
                  marginBottom: 6,
                }}>{s.title}</div>
                {s.prompt && (
                  <div style={{
                    fontFamily: theme.fontMono, fontSize: 10, color: theme.muted,
                    letterSpacing: 0.5, marginBottom: 8, fontStyle: 'italic',
                  }}>"{s.prompt.toUpperCase()}"</div>
                )}
                <div style={{
                  fontFamily: theme.fontBody, fontSize: 13, color: theme.muted,
                  lineHeight: 1.5, whiteSpace: 'pre-wrap',
                  display: '-webkit-box', WebkitLineClamp: 3, WebkitBoxOrient: 'vertical',
                  overflow: 'hidden',
                }}>{s.text}</div>
                <div style={{
                  display: 'flex', gap: 14, marginTop: 10,
                  paddingTop: 10, borderTop: `1px solid ${theme.border}`,
                }}>
                  <button style={{
                    background: 'transparent', border: 'none', padding: 0,
                    color: theme.text, cursor: 'pointer',
                    fontFamily: theme.fontMono, fontSize: 10, fontWeight: 700,
                    letterSpacing: 1, textTransform: 'uppercase',
                  }}>OPEN ↗</button>
                  <button style={{
                    background: 'transparent', border: 'none', padding: 0,
                    color: theme.muted, cursor: 'pointer',
                    fontFamily: theme.fontMono, fontSize: 10, fontWeight: 700,
                    letterSpacing: 1, textTransform: 'uppercase',
                  }}>SHARE TO FEED</button>
                  <button onClick={() => removeSub(s.id)} style={{
                    background: 'transparent', border: 'none', padding: 0,
                    color: theme.faint, cursor: 'pointer', marginLeft: 'auto',
                    fontFamily: theme.fontMono, fontSize: 10, fontWeight: 700,
                    letterSpacing: 1, textTransform: 'uppercase',
                  }}>DELETE</button>
                </div>
              </Card>
            ))}
          </div>
        )}
      </div>

      {/* ░░ stats footer */}
      <div style={{
        padding: `${theme.gap + 6}px ${theme.pad}px 0`,
        display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8,
      }}>
        {[
          { n: weeklySubs.length, l: 'WEEKLY\nENTRIES' },
          { n: dailySubs.length,  l: 'DAILY\nLOGS' },
          { n: PROMPTS.length,    l: 'PROMPTS\nIN BANK' },
        ].map((s, i) => (
          <Card key={i} theme={theme} style={{ padding: 12 }}>
            <div style={{ fontFamily: theme.fontDisplay, fontSize: 26, color: theme.text, lineHeight: 1, letterSpacing: -0.3 }}>
              {s.n}
            </div>
            <div style={{
              fontFamily: theme.fontMono, fontSize: 9, color: theme.muted,
              letterSpacing: 0.8, marginTop: 6, whiteSpace: 'pre-line',
              lineHeight: 1.3, fontWeight: 600,
            }}>{s.l}</div>
          </Card>
        ))}
      </div>

      {/* ░░ COMPOSER MODAL */}
      {composer && (
        <ComposerSheet
          theme={theme}
          kind={composer}
          prompt={composer === 'weekly' ? WEEKLY_CHALLENGE.title : PROMPTS[promptIdx]}
          onClose={() => setComposer(null)}
          onSubmit={submit}
        />
      )}

      {/* ░░ COMMUNITY MODAL */}
      {community && (
        <CommunityPanel theme={theme} onClose={() => setCommunity(false)} />
      )}

      {/* ░░ TOAST */}
      {toast && (
        <div style={{
          position: 'absolute', bottom: 100, left: '50%', transform: 'translateX(-50%)',
          background: theme.text, color: theme.bg,
          padding: '12px 18px', borderRadius: 99,
          fontFamily: theme.fontMono, fontSize: 11, fontWeight: 700,
          letterSpacing: 1, zIndex: 90,
          boxShadow: '0 8px 24px rgba(0,0,0,0.3)',
          animation: 'toastIn .25s cubic-bezier(.2,.8,.2,1)',
        }}>
          ✓ {toast}
          <style>{`@keyframes toastIn { from { opacity: 0; transform: translate(-50%, 12px); } to { opacity: 1; transform: translate(-50%, 0); } }`}</style>
        </div>
      )}
    </div>
  );
}

window.LAUNCH_SCREENS_9 = { CreateScreen };
