/* Brainstorm X — Naming wizard. Controlled, persists a real session. */
(function () {
  const { useState } = React;
  const DS = window.BrainstormXDesignSystem_f2a458;
  const { Button, Card, Input, Textarea, Chip, SentimentSlider, ProgressSteps } = DS;
  const I = window.BXIcons;

  const STEPS = ['Basics', 'Keywords', 'Feeling', 'Style', 'Review'];
  const PROJECT_TYPES = ['Business name', 'Product name', 'App / platform', 'Service name', 'Event name', 'Campaign name'];
  const QUICK_CHIPS = ['Fun', 'Clever', 'Clean', 'Technical', 'Luxurious', 'Quirky', 'Warm', 'Direct', 'Inventive', 'Trustworthy'];
  const STYLE_OPTS = [
    ['Brandable', 'Invented, like Google'], ['Evocative', 'Energy, like Red Bull'],
    ['Short phrase', 'Like Dollar Shave Club'], ['Compound', 'Blended, like FedEx'],
    ['Alternate spelling', 'Like Lyft'], ['Real words', 'Like Apple'],
  ];
  const AXES = [['Playful', 'Serious', 'Playful'], ['Premium', 'Affordable', 'Premium'], ['Minimal', 'Expressive', 'Minimal'], ['Safe', 'Unusual', 'Safe']];

  function Shell({ step, children, onBack, onNext, nextLabel, canBack, busy }) {
    return (
      <div className="bx-nebula-bg" style={{ minHeight: '100vh', display: 'flex', flexDirection: 'column', alignItems: 'center', padding: '36px 24px 110px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 26 }}>
          <img src="../assets/mark-spark.svg" width="28" height="28" alt="" />
          <span style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 18, color: 'var(--text-1)' }}>Brainstorm<span className="bx-text-nebula"> X</span></span>
        </div>
        <div style={{ width: 'min(720px, 100%)', marginBottom: 26 }}>
          <ProgressSteps current={step} steps={STEPS} />
        </div>
        <Card glass style={{ width: 'min(720px, 100%)', padding: '32px 34px' }}>
          {children}
          <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 30 }}>
            <Button variant="ghost" onClick={onBack} iconLeft={<I.ArrowLeft size={18} />}>{canBack ? 'Back' : 'Cancel'}</Button>
            <Button onClick={onNext} disabled={busy} iconRight={<I.ArrowRight size={18} />}>{busy ? 'Generating…' : (nextLabel || 'Continue')}</Button>
          </div>
        </Card>
      </div>
    );
  }

  function Field({ label, children, hint }) {
    return (
      <div style={{ marginBottom: 18 }}>
        <div style={{ fontFamily: 'var(--font-sans)', fontSize: 14, fontWeight: 600, color: 'var(--text-2)', marginBottom: 9 }}>{label}</div>
        {children}
        {hint && <div style={{ fontSize: 12, color: 'var(--text-3)', marginTop: 7 }}>{hint}</div>}
      </div>
    );
  }

  function Wizard({ initial, onComplete, onCancel, busy }) {
    const init = initial || {};
    const [step, setStep] = useState(0);
    const [project, setProject] = useState(init.project || '');
    const [type, setType] = useState(init.type || 'Business name');
    const [industry, setIndustry] = useState(init.industry || '');
    const [audience, setAudience] = useState(init.audience || '');
    const [description, setDescription] = useState(init.description || '');
    const [kw, setKw] = useState(init.keywordsList || []);
    const [kwInput, setKwInput] = useState('');
    const [avoid, setAvoid] = useState(init.avoid || []);
    const [avoidInput, setAvoidInput] = useState('');
    const [styles, setStyles] = useState(() => {
      const o = {}; (init.styles || ['Brandable', 'Evocative', 'Compound']).forEach((s) => { o[s] = true; }); return o;
    });
    const [chips, setChips] = useState(() => {
      const o = {}; (init.chips || ['Quirky', 'Fun']).forEach((c) => { o[c] = true; }); return o;
    });
    const [axes, setAxes] = useState(() => AXES.map(([l, r, key]) => (init.personality && init.personality[key] != null ? init.personality[key] : 50)));
    const [randomness, setRandomness] = useState(init.randomness || 'Medium');

    const editing = !!initial;
    const last = STEPS.length - 1;
    const toggle = (obj, set, k) => set({ ...obj, [k]: !obj[k] });
    const addKw = (e) => { e.preventDefault(); const v = kwInput.trim(); if (v && !kw.includes(v)) setKw([...kw, v]); setKwInput(''); };
    const addAvoid = (e) => { e.preventDefault(); const v = avoidInput.trim(); if (v && !avoid.includes(v)) setAvoid([...avoid, v]); setAvoidInput(''); };

    const back = () => (step > 0 ? setStep(step - 1) : onCancel && onCancel());
    const next = () => {
      if (step < last) { setStep(step + 1); return; }
      const personality = {};
      AXES.forEach(([l, r, key], i) => { personality[key] = axes[i]; });
      onComplete && onComplete({
        project: project.trim() || 'Untitled session', type, industry: industry.trim(), audience: audience.trim(),
        description: description.trim(), keywordsList: kw, avoid, randomness, personality,
        styles: Object.keys(styles).filter((k) => styles[k]),
        chips: Object.keys(chips).filter((k) => chips[k]),
      });
    };

    const heads = [
      ['What are you naming?', "Let's train your naming session — answer a few quick questions and we'll generate your first set of ideas."],
      ['Add your keywords', 'Add words, themes or existing names that point the AI in the right direction.'],
      ['Feeling & personality', 'Slide towards the qualities that fit your brand. Add a few quick chips too.'],
      ['Name style', 'Pick one or more styles. You can always change this later.'],
      ['Review & generate', "Check your brief — we'll generate your first wave of names and open the arena."],
    ];

    const nextLabel = step === last ? (editing ? 'Save & continue' : 'Generate first wave') : 'Continue';

    return (
      <Shell step={step} onBack={back} onNext={next} canBack={step > 0} nextLabel={nextLabel} busy={busy}>
        <span className="bx-eyebrow">Step {step + 1} of {STEPS.length}</span>
        <h2 style={{ fontSize: 28, margin: '10px 0 6px' }}>{heads[step][0]}</h2>
        <p style={{ fontSize: 15, color: 'var(--text-2)', marginBottom: 24 }}>{heads[step][1]}</p>

        {step === 0 && (<>
          <Field label="Project name"><Input placeholder="New pet accessories shop" value={project} onChange={(e) => setProject(e.target.value)} /></Field>
          <Field label="Naming type">
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 9 }}>
              {PROJECT_TYPES.map((tp) => <Chip key={tp} selected={type === tp} onClick={() => setType(tp)}>{tp}</Chip>)}
            </div>
          </Field>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
            <Field label="Industry"><Input placeholder="Pet products" value={industry} onChange={(e) => setIndustry(e.target.value)} /></Field>
            <Field label="Target audience"><Input placeholder="UK dog & cat owners" value={audience} onChange={(e) => setAudience(e.target.value)} /></Field>
          </div>
          <Field label="Short description"><Textarea rows={2} placeholder="A fun online shop selling colourful, playful pet accessories." value={description} onChange={(e) => setDescription(e.target.value)} /></Field>
        </>)}

        {step === 1 && (<>
          <Field label="Main keywords" hint="Press enter to add. These become boostable orbs in the arena.">
            <form onSubmit={addKw} style={{ marginBottom: 12 }}>
              <Input placeholder="Type a keyword and press enter…" value={kwInput} onChange={(e) => setKwInput(e.target.value)} iconLeft={<I.Plus size={18} />} />
            </form>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 9 }}>
              {kw.length === 0 && <span style={{ fontSize: 13, color: 'var(--text-3)' }}>No keywords yet — add a few above.</span>}
              {kw.map((k) => <Chip key={k} selected onRemove={() => setKw(kw.filter((x) => x !== k))}>{k}</Chip>)}
            </div>
          </Field>
          <Field label="Words to avoid">
            <form onSubmit={addAvoid} style={{ marginBottom: 12 }}>
              <Input placeholder="Type a word to avoid and press enter…" value={avoidInput} onChange={(e) => setAvoidInput(e.target.value)} iconLeft={<I.X size={18} />} />
            </form>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 9 }}>
              {avoid.map((k) => <Chip key={k} accent="var(--cold-cool)" onRemove={() => setAvoid(avoid.filter((x) => x !== k))}>{k}</Chip>)}
            </div>
          </Field>
        </>)}

        {step === 2 && (<>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '20px 32px', marginBottom: 22 }}>
            {AXES.map(([l, r], i) => (
              <SentimentSlider key={l} leftLabel={l} rightLabel={r} value={axes[i]}
                accent={i % 2 ? 'var(--neon-cyan)' : 'var(--neon-violet)'}
                onChange={(v) => setAxes(axes.map((a, j) => (j === i ? v : a)))} />
            ))}
          </div>
          <Field label="Quick chips">
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 9 }}>
              {QUICK_CHIPS.map((c) => <Chip key={c} selected={!!chips[c]} onClick={() => toggle(chips, setChips, c)}>{c}</Chip>)}
            </div>
          </Field>
        </>)}

        {step === 3 && (<>
          <Field label="Name styles">
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
              {STYLE_OPTS.map(([name, eg]) => {
                const on = !!styles[name];
                return (
                  <button key={name} onClick={() => toggle(styles, setStyles, name)} style={{
                    textAlign: 'left', cursor: 'pointer', padding: '14px 16px', borderRadius: 'var(--radius-md)',
                    background: on ? 'color-mix(in srgb, var(--neon-cyan) 12%, transparent)' : 'var(--surface-2)',
                    border: `1px solid ${on ? 'var(--neon-cyan)' : 'var(--line-2)'}`,
                    boxShadow: on ? '0 0 16px color-mix(in srgb, var(--neon-cyan) 30%, transparent)' : 'none',
                    transition: 'all var(--dur-base) var(--ease-out)',
                  }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                      <span style={{ fontFamily: 'var(--font-sans)', fontWeight: 700, color: on ? 'var(--neon-cyan)' : 'var(--text-1)' }}>{name}</span>
                      {on && <span style={{ color: 'var(--neon-cyan)' }}><I.Check size={16} /></span>}
                    </div>
                    <div style={{ fontSize: 12, color: 'var(--text-3)', marginTop: 4, fontFamily: 'var(--font-mono)' }}>{eg}</div>
                  </button>
                );
              })}
            </div>
          </Field>
          <Field label="Randomness" hint="Higher means more unexpected, creative ideas.">
            <div style={{ display: 'flex', gap: 9 }}>
              {['Low', 'Medium', 'High'].map((r) => <Chip key={r} selected={randomness === r} accent="var(--neon-magenta)" onClick={() => setRandomness(r)}>{r}</Chip>)}
            </div>
          </Field>
        </>)}

        {step === 4 && (<>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            <ReviewRow label="Project" value={project || 'Untitled session'} />
            <ReviewRow label="Type" value={type} />
            {industry && <ReviewRow label="Industry" value={industry} />}
            {audience && <ReviewRow label="Audience" value={audience} />}
            <ReviewRow label="Keywords" value={kw.length ? kw.join(', ') : 'none yet'} />
            {avoid.length > 0 && <ReviewRow label="Avoid" value={avoid.join(', ')} />}
            <ReviewRow label="Styles" value={Object.keys(styles).filter((k) => styles[k]).join(', ') || 'Brandable'} />
            <ReviewRow label="Randomness" value={randomness} />
          </div>
          <div style={{ display: 'flex', gap: 10, alignItems: 'center', padding: '14px 16px', borderRadius: 'var(--radius-md)', background: 'var(--surface-inset)', border: '1px solid var(--line-1)', marginTop: 16 }}>
            <span style={{ color: 'var(--neon-lime)' }}><I.Check size={18} /></span>
            <span style={{ fontSize: 14, color: 'var(--text-2)' }}>Ready — we'll generate your first wave of names and open the <strong style={{ color: 'var(--text-1)' }}>Name Arena</strong>.</span>
          </div>
        </>)}
      </Shell>
    );
  }

  function ReviewRow({ label, value }) {
    return (
      <div style={{ display: 'flex', gap: 14, alignItems: 'baseline', padding: '8px 0', borderBottom: '1px solid var(--line-1)' }}>
        <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '0.08em', width: 110, flex: 'none' }}>{label}</span>
        <span style={{ fontSize: 15, color: 'var(--text-1)' }}>{value}</span>
      </div>
    );
  }

  window.BXWizard = Wizard;
})();
