/* Brainstorm X — Name Arena. The signature live 3D-ish naming space. */
(function () {
  const { useState, useRef } = React;
  const DS = window.BrainstormXDesignSystem_f2a458;
  const { Button, Card, NameCard, KeywordOrb, Badge, Avatar, AvatarStack, IconButton } = DS;
  const I = window.BXIcons;
  const heatFromScore = window.BXheatFromScore;

  const SCALE = { on_fire: 1.0, hot: 0.94, warm: 0.86, neutral: 0.82, cold: 0.78, frozen: 0.7 };
  const VOTE_DELTA = { up: 2, down: -2, fire: 3, ice: -3 };

  function Stars({ n = 60 }) {
    const stars = React.useMemo(() => Array.from({ length: n }, () => ({
      top: Math.random() * 100, left: Math.random() * 100, s: Math.random() * 2 + 1,
      o: Math.random() * 0.6 + 0.15, glow: Math.random() > 0.88,
    })), [n]);
    return <div style={{ position: 'absolute', inset: 0, overflow: 'hidden', pointerEvents: 'none' }}>
      {stars.map((s, i) => <span key={i} style={{ position: 'absolute', top: s.top + '%', left: s.left + '%', width: s.s, height: s.s, borderRadius: '50%', background: '#fff', opacity: s.o, boxShadow: s.glow ? '0 0 6px var(--neon-cyan)' : 'none' }} />)}
    </div>;
  }

  function Header({ wave, onGenerate, generating, goto }) {
    return (
      <header style={{
        position: 'absolute', top: 0, left: 0, right: 0, zIndex: 30, display: 'flex', alignItems: 'center',
        justifyContent: 'space-between', padding: '14px 22px', gap: 16,
        background: 'rgba(10,10,24,0.5)', borderBottom: '1px solid var(--line-1)',
        backdropFilter: 'blur(18px)', WebkitBackdropFilter: 'blur(18px)',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
          <img src="../../assets/mark-spark.svg" width="28" height="28" alt="" />
          <div>
            <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 15, color: 'var(--text-1)', lineHeight: 1.1 }}>Pickle Paws</div>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '0.08em' }}>Name Arena · Wave {wave}</div>
          </div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
            <AvatarStack people={window.BXpeople} max={4} size={30} />
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 12, color: 'var(--text-3)', fontFamily: 'var(--font-mono)' }}>
              <span style={{ width: 7, height: 7, borderRadius: '50%', background: 'var(--neon-lime)', boxShadow: '0 0 8px var(--neon-lime)' }} />3 live
            </span>
          </div>
          <Button variant="secondary" size="sm" onClick={() => goto('shortlist')} iconLeft={<I.Star size={16} />}>Shortlist</Button>
          <Button variant="fire" size="md" onClick={onGenerate} disabled={generating} iconLeft={<I.Zap size={18} />}>
            {generating ? 'Evolving…' : 'Generate next wave'}
          </Button>
        </div>
      </header>
    );
  }

  function KeywordRail({ keywords, onBoost }) {
    return (
      <div style={{
        position: 'absolute', left: 18, top: '50%', transform: 'translateY(-50%)', zIndex: 25,
        display: 'flex', flexDirection: 'column', gap: 14, padding: '18px 14px',
        background: 'var(--surface-glass)', border: '1px solid var(--line-2)', borderRadius: 'var(--radius-xl)',
        backdropFilter: 'blur(18px)', WebkitBackdropFilter: 'blur(18px)', boxShadow: 'var(--shadow-lg)',
      }}>
        <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '0.1em', textAlign: 'center' }}>Keywords</div>
        {keywords.map((k) => <KeywordOrb key={k.id} {...k} onBoost={() => onBoost(k.id)} />)}
      </div>
    );
  }

  function ActivityFeed({ events }) {
    return (
      <div style={{
        position: 'absolute', right: 18, bottom: 84, zIndex: 25, width: 260, maxHeight: 200, overflow: 'hidden',
        padding: '14px 16px', background: 'var(--surface-glass)', border: '1px solid var(--line-2)',
        borderRadius: 'var(--radius-lg)', backdropFilter: 'blur(18px)', WebkitBackdropFilter: 'blur(18px)', boxShadow: 'var(--shadow-lg)',
      }}>
        <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: 10 }}>Activity</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
          {events.slice(0, 5).map((e, i) => (
            <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12.5, color: 'var(--text-2)' }}>
              <Avatar name={e.who} size={20} />
              <span><strong style={{ color: 'var(--text-1)' }}>{e.who.split(' ')[0]}</strong> {e.what}</span>
            </div>
          ))}
        </div>
      </div>
    );
  }

  function DetailPanel({ name, onClose, onVote }) {
    const variants = ['More like this', 'Make it shorter', 'More premium', 'More playful'];
    return (
      <div style={{
        position: 'absolute', top: 0, right: 0, bottom: 0, width: 360, zIndex: 40, padding: '78px 26px 26px',
        background: 'var(--surface-glass-strong)', borderLeft: '1px solid var(--line-2)',
        backdropFilter: 'blur(24px)', WebkitBackdropFilter: 'blur(24px)', boxShadow: 'var(--shadow-xl)',
        overflowY: 'auto', animation: 'bxFloat 0s',
      }}>
        <div style={{ position: 'absolute', top: 82, right: 22 }}>
          <IconButton label="Close" variant="ghost" onClick={onClose}><I.X size={18} /></IconButton>
        </div>
        <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '0.1em' }}>{name.style}</span>
        <h2 style={{ fontSize: 38, margin: '8px 0 4px' }}>{name.name}</h2>
        <div style={{ fontFamily: 'var(--font-mono)', fontSize: 13, color: 'var(--text-3)', marginBottom: 16 }}>{name.pronunciation}</div>
        <p style={{ fontSize: 15, color: 'var(--text-2)', lineHeight: 1.5, marginBottom: 18 }}>{name.reason}</p>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 7, marginBottom: 18 }}>
          {name.keywords.map((k) => <Badge key={k} tone="cyan" mono>{k}</Badge>)}
        </div>
        <div style={{ display: 'flex', gap: 8, marginBottom: 20 }}>
          <div style={{ flex: 1, padding: '10px 12px', borderRadius: 'var(--radius-md)', background: 'var(--surface-inset)', border: '1px solid var(--line-1)' }}>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--text-3)' }}>SCORE</div>
            <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 24, color: 'var(--heat-fire)' }}>{name.score > 0 ? '+' + name.score : name.score}</div>
          </div>
          <div style={{ flex: 1, padding: '10px 12px', borderRadius: 'var(--radius-md)', background: 'var(--surface-inset)', border: '1px solid var(--line-1)' }}>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--text-3)' }}>CONFIDENCE</div>
            <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 24, color: 'var(--neon-cyan)' }}>{name.confidence}%</div>
          </div>
        </div>
        <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: 10 }}>Evolve this name</div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginBottom: 22 }}>
          {variants.map((v) => <Button key={v} variant="secondary" size="sm" iconLeft={<I.Sparkles size={15} />}>{v}</Button>)}
        </div>
        <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: 10 }}>Comments</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          <div style={{ display: 'flex', gap: 9 }}><Avatar name="Alex Roy" size={26} /><div style={{ fontSize: 13.5, color: 'var(--text-2)', background: 'var(--surface-2)', padding: '8px 12px', borderRadius: 'var(--radius-md)' }}>I like how short this is.</div></div>
          <div style={{ display: 'flex', gap: 9 }}><Avatar name="Priya N" size={26} /><div style={{ fontSize: 13.5, color: 'var(--text-2)', background: 'var(--surface-2)', padding: '8px 12px', borderRadius: 'var(--radius-md)' }}>Works for a .co.uk domain too 👍</div></div>
        </div>
      </div>
    );
  }

  function Arena({ names, setNames, keywords, setKeywords, wave, setWave, goto }) {
    const [openId, setOpenId] = useState(null);
    const [generating, setGenerating] = useState(false);
    const [events, setEvents] = useState([
      { who: 'Sam Lee', what: 'boosted "quirky"' },
      { who: 'Alex Roy', what: 'shortlisted "Pawlio"' },
      { who: 'Priya N', what: 'upvoted "Snugglo"' },
    ]);

    const vote = (id, type) => {
      setNames((ns) => ns.map((n) => {
        if (n.id !== id) return n;
        if (type === 'star') {
          const sl = !n.shortlisted; const score = n.score + (sl ? 5 : -5);
          return { ...n, shortlisted: sl, score, heat: heatFromScore(score) };
        }
        const score = n.score + (VOTE_DELTA[type] || 0);
        const counts = { ...n.counts, [type]: (n.counts[type] || 0) + 1 };
        return { ...n, score, counts, heat: heatFromScore(score) };
      }));
      const labels = { up: 'upvoted', down: 'downvoted', fire: 'set 🔥 on', ice: 'cooled', star: 'shortlisted' };
      const nm = names.find((n) => n.id === id);
      setEvents((ev) => [{ who: 'You', what: `${labels[type]} "${nm ? nm.name : ''}"` }, ...ev]);
    };

    const boost = (id) => {
      setKeywords((ks) => ks.map((k) => k.id === id ? { ...k, weight: k.weight + 1, count: (k.count || 0) + 1, state: k.state === 'avoid' ? 'avoid' : 'boosted' } : k));
      const kw = keywords.find((k) => k.id === id);
      setEvents((ev) => [{ who: 'You', what: `boosted "${kw ? kw.label : ''}"` }, ...ev]);
    };

    const generate = () => {
      setGenerating(true);
      setTimeout(() => {
        const batch = [
          { id: 'pip-' + wave, name: 'Pippa & Co', style: 'short_phrase', pronunciation: 'pip-uh', reason: 'Playful, personable and clearly British in tone.', keywords: ['quirky', 'warm'], confidence: 77, score: 6, counts: { up: 4, down: 0, fire: 1, ice: 0 }, x: 40, y: 24, heat: 'hot', fresh: true },
          { id: 'wag-' + wave, name: 'Waggle', style: 'real_word', pronunciation: 'wag-uhl', reason: 'Fun, energetic and easy to remember for a pet brand.', keywords: ['playful', 'fun'], confidence: 73, score: 4, counts: { up: 3, down: 0, fire: 0, ice: 0 }, x: 56, y: 70, heat: 'warm', fresh: true },
        ];
        setNames((ns) => [...ns.map((n) => ({ ...n, fresh: false })), ...batch]);
        setWave((w) => w + 1);
        setEvents((ev) => [{ who: 'Brainstorm X', what: `generated Wave ${wave + 1}` }, ...ev]);
        setGenerating(false);
      }, 1100);
    };

    const open = names.find((n) => n.id === openId);

    return (
      <div className="bx-nebula-bg" style={{ position: 'relative', height: '100vh', overflow: 'hidden' }}>
        <Stars n={70} />
        <Header wave={wave} onGenerate={generate} generating={generating} goto={goto} />
        <KeywordRail keywords={keywords} onBoost={boost} />

        {/* scene */}
        <div style={{ position: 'absolute', inset: '70px 360px 0 150px' }}>
          {names.map((n) => {
            const sc = (SCALE[n.heat] || 0.82);
            return (
              <div key={n.id} style={{
                position: 'absolute', left: n.x + '%', top: n.y + '%', transform: 'translate(-50%,-50%)',
                animation: n.fresh ? 'bxDrop 0.6s var(--ease-spring)' : 'none', zIndex: openId === n.id ? 20 : 10,
              }}>
                <NameCard {...n} scale={sc} floating selected={openId === n.id}
                  activeVotes={n.counts && n.counts.up > 0 ? {} : {}}
                  onVote={(t) => vote(n.id, t)} onOpen={() => setOpenId(n.id)} />
              </div>
            );
          })}
        </div>

        <ActivityFeed events={events} />
        {open && <DetailPanel name={open} onClose={() => setOpenId(null)} onVote={vote} />}

        {/* intro tooltip */}
        <div style={{ position: 'absolute', left: 150, bottom: 18, zIndex: 22, maxWidth: 360, padding: '12px 16px', background: 'var(--surface-glass)', border: '1px solid var(--line-2)', borderRadius: 'var(--radius-md)', backdropFilter: 'blur(18px)', WebkitBackdropFilter: 'blur(18px)' }}>
          <span style={{ fontSize: 13, color: 'var(--text-2)' }}>
            <strong style={{ color: 'var(--neon-cyan)' }}>Welcome to your Name Arena.</strong> Vote on names and boost keywords — liked names grow and glow, weak ones cool down.
          </span>
        </div>
      </div>
    );
  }

  // drop-in keyframe
  if (!document.getElementById('bx-arena-extra')) {
    const s = document.createElement('style'); s.id = 'bx-arena-extra';
    s.textContent = '@keyframes bxDrop{0%{transform:translate(-50%,-90%) scale(0.4);opacity:0}100%{transform:translate(-50%,-50%) scale(1);opacity:1}}';
    document.head.appendChild(s);
  }

  window.BXArena = Arena;
})();
