/* Studio 76 — The Imaginarium (standalone). Dream a piece → rendered in solid gold.
   Beyond the edit box: Surprise me, a muse builder, and birthstone designs.
   Talks only to imaginarium.php (brief → hero → wireframe → metal variants). */

const MOODS = ['Celestial','Midnight','Monsoon','Golden hour','Oceanic','Ember','Botanical','Gothic romance','New-age minimal','Maximalist'];
const ERAS  = ['Art Deco','Victorian','Mughal','1970s','Y2K','Ancient Rome','Belle Époque','Future-organic'];
const GEMS  = ['Emerald','Ruby','Sapphire','Diamond','Pearl','Opal','Moonstone','Black diamond','Pink tourmaline','Tanzanite'];
const FORMS = ['Ring','Necklace','Earrings','Cuff','Pendant','Anklet','Brooch','Tiara'];
const OCCASIONS = ['an engagement','an anniversary','a self-gift','an everyday heirloom','the red carpet','a wedding'];

const MONTHS = [
  ['Jan','Garnet'],['Feb','Amethyst'],['Mar','Aquamarine'],['Apr','Diamond'],
  ['May','Emerald'],['Jun','Moonstone'],['Jul','Ruby'],['Aug','Peridot'],
  ['Sep','Sapphire'],['Oct','Opal'],['Nov','Citrine'],['Dec','Tanzanite'],
];

/* curated, gorgeous seeds for Surprise me */
const DREAMS = [
  'A celestial diamond choker scattered like a constellation across the collarbone',
  'An Art Deco emerald cocktail ring, stepped and architectural, on a slim band',
  'A monsoon-grey moonstone pendant that glows like rain on glass',
  'Twin serpent ear-climbers in brushed gold with tiny ruby eyes',
  'A Mughal-inspired polki necklace reimagined fine, delicate and barely-there',
  'A single pear-cut sapphire suspended on a thread-thin chain, floating at the throat',
  'A molten gold cuff that looks poured rather than made, holding one raw emerald',
  'Stacking rings like the phases of the moon — pavé to bare polished gold',
  'A Belle Époque garland melted into a delicate everyday tiara of white gold',
  'Black diamond studs ringed in a whisper of white-gold thorns',
  'A botanical vine bracelet, gold leaves curling around a line of tsavorites',
  'An ember-orange spessartite solitaire in a fine six-prong, warm as candlelight',
];

const EXAMPLES = [
  'A fine rose-gold pendant with a single pearl — modern and minimal',
  'Delicate diamond ear-climbers, contemporary, barely-there',
  'A slim stacking ring with a tiny emerald, new-age and clean',
];

const TONES = [
  { k:'original', label:'As designed' },
  { k:'yellow',   label:'Yellow' },
  { k:'white',    label:'White' },
  { k:'rose',     label:'Rose' },
];

async function api(action, payload){
  const r = await fetch('imaginarium.php',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(Object.assign({action},payload))});
  let j={}; try{ j=await r.json(); }catch(e){}
  if(!r.ok || j.error) throw new Error(j.error || ('Something went wrong ('+r.status+')'));
  return j;
}
function pick(a){ return a[Math.floor(Math.random()*a.length)]; }
const isUrl = x => typeof x === 'string' && x !== 'loading';

function Imaginarium(){
  const [tab, setTab]   = React.useState('muse');     // muse | stars | words
  const [muse, setMuse] = React.useState({ mood:null, era:null, gem:null, form:null, occ:null });
  const [month, setMonth] = React.useState(null);
  const [dream, setDream] = React.useState('');

  const [phase, setPhase] = React.useState('idle');    // idle | thinking | result
  const [concept, setConcept] = React.useState(null);
  const [spec, setSpec] = React.useState(null);
  const [hero, setHero] = React.useState(null);
  const [variants, setVariants] = React.useState({});
  const [wire, setWire] = React.useState(null);
  const [active, setActive] = React.useState('original');
  const [view, setView] = React.useState('render');
  const [err, setErr] = React.useState('');
  const heroRef = React.useRef(null);

  function toggle(dim, val){ setMuse(m => Object.assign({}, m, { [dim]: m[dim] === val ? null : val })); }

  function composeMuse(){
    const m = muse;
    var s = 'A ' + (m.form ? m.form.toLowerCase() : 'fine jewellery piece');
    if (m.occ) s += ' for ' + m.occ;
    var clauses = [];
    if (m.mood) clauses.push(m.mood.toLowerCase() + ' in feeling');
    if (m.era)  clauses.push('inspired by ' + m.era);
    if (m.gem)  clauses.push('centred on ' + m.gem.toLowerCase());
    if (clauses.length) s += ', ' + clauses.join(', ');
    s += '. New-age, fine and wearable — made to be cast in solid gold.';
    return s;
  }
  const museHasAny = muse.mood || muse.era || muse.gem || muse.form || muse.occ;

  async function imagine(text){
    const d = (text || '').trim();
    if (d.length < 4){ setErr('Tell us a little more about the piece.'); return; }
    setErr(''); setPhase('thinking');
    setConcept(null); setSpec(null); setHero(null); heroRef.current = null;
    setVariants({}); setWire(null); setActive('original'); setView('render');
    try{
      const b = await api('brief', { dream: d });
      setConcept(b.concept); setSpec(b.spec); setPhase('result');
      const h = await api('hero', { spec: b.spec });
      heroRef.current = h; setHero(h); setVariants({ original: h.dataUrl });
      // Blueprint + metal variants are generated ON DEMAND (when tapped) — no wasted renders.
    }catch(e){ setErr(e.message || 'Could not imagine that — try again.'); setPhase('idle'); }
  }

  // on-demand: blueprint
  function genWire(){
    setView('blueprint');
    if (wire || !heroRef.current) return;
    setWire('loading');
    api('wireframe', { id: heroRef.current.id }).then(w => setWire(w.dataUrl)).catch(() => setWire(null));
  }
  // on-demand: a metal variant (original is already the hero)
  function genVariant(tone){
    setActive(tone); setView('render');
    if (tone === 'original' || variants[tone] || !heroRef.current) return;
    setVariants(v => Object.assign({}, v, { [tone]: 'loading' }));
    api('variant', { id: heroRef.current.id, tone })
      .then(r => setVariants(v => Object.assign({}, v, { [tone]: r.dataUrl })))
      .catch(() => setVariants(v => { const n = Object.assign({}, v); delete n[tone]; return n; }));
  }

  function surprise(){
    // 70% a curated gem of a dream, 30% a freshly-rolled muse
    if (Math.random() < 0.7){ imagine(pick(DREAMS)); return; }
    const m = { form: pick(FORMS), gem: pick(GEMS), mood: pick(MOODS), era: pick(ERAS), occ: null };
    setMuse(m); setTab('muse');
    imagine('A ' + m.form.toLowerCase() + ', ' + m.mood.toLowerCase() + ' in feeling, inspired by ' + m.era + ', centred on ' + m.gem.toLowerCase() + '. New-age, fine and wearable — made to be cast in solid gold.');
  }

  function imagineBirthstone(){
    const mo = MONTHS[month];
    if (!mo) return;
    imagine('A fine, contemporary piece designed around a ' + mo[1].toLowerCase() + ' — the birthstone of ' + ({Jan:'January',Feb:'February',Mar:'March',Apr:'April',May:'May',Jun:'June',Jul:'July',Aug:'August',Sep:'September',Oct:'October',Nov:'November',Dec:'December'})[mo[0]] + '. Let the stone lead, set in solid gold, new-age and wearable every day.');
  }

  const fmtStone = s => s ? [s.carat_estimate, s.cut, s.color, s.type].filter(Boolean).join(' ') : '';
  const fmtAcc = a => (a && a.length) ? a.map(x => typeof x === 'string' ? x : [x.cut, x.color, x.type].filter(Boolean).join(' ')).filter(Boolean).join(', ') : '';
  const mainSrc = view === 'blueprint' ? (isUrl(wire) ? wire : null) : (isUrl(variants[active]) ? variants[active] : (hero && hero.dataUrl));
  const stageMsg = !concept ? 'Composing your concept…' : (!hero ? 'Rendering in solid gold…' : (view === 'blueprint' ? 'Drafting the blueprint…' : 'Rendering in solid gold…'));
  const Row = ({l,v}) => v ? <div className="im-row"><span className="im-k">{l}</span><span className="im-v">{v}</span></div> : null;

  return (
    <main className="im">
      <header className="im-head">
        <a className="im-logo" href="/">Studio<span> 76</span></a>
        <span className="im-links"><a href="/blueprint.html">Bench</a><a href="/stylist.html">Stylist</a><a href="/tryiton.html">Try-on</a><span className="im-eyebrow">✦ Imaginarium</span></span>
      </header>

      <section className="im-hero">
        <h1 className="im-title">Dream it. We’ll draw it <span className="it">in gold.</span></h1>
        <p className="im-sub">Describe a piece you’ve always wanted — or let a muse spark it — and watch it render in solid gold, in seconds. No photo needed; just your imagination.</p>
      </section>

      <div className="spark">
        <button className="spark-surprise" onClick={surprise} disabled={phase === 'thinking'}>
          <span>✦</span> {phase === 'thinking' ? 'Conjuring…' : 'Surprise me — conjure a piece'} <span>✦</span>
        </button>
        <div className="spark-or"><span>or spark your own</span></div>

        <div className="im-tabs">
          <button className={'im-tab' + (tab==='muse'?' on':'')} onClick={()=>setTab('muse')}>Build a muse</button>
          <button className={'im-tab' + (tab==='stars'?' on':'')} onClick={()=>setTab('stars')}>By the stars</button>
          <button className={'im-tab' + (tab==='words'?' on':'')} onClick={()=>setTab('words')}>In your words</button>
        </div>

        {tab === 'muse' && (
          <div>
            <div className="im-dim"><span className="im-dim-l">The form</span><div className="im-chips">{FORMS.map(f => <button key={f} className={'im-chip'+(muse.form===f?' on':'')} onClick={()=>toggle('form',f)}>{f}</button>)}</div></div>
            <div className="im-dim"><span className="im-dim-l">A feeling</span><div className="im-chips">{MOODS.map(f => <button key={f} className={'im-chip'+(muse.mood===f?' on':'')} onClick={()=>toggle('mood',f)}>{f}</button>)}</div></div>
            <div className="im-dim"><span className="im-dim-l">An era</span><div className="im-chips">{ERAS.map(f => <button key={f} className={'im-chip'+(muse.era===f?' on':'')} onClick={()=>toggle('era',f)}>{f}</button>)}</div></div>
            <div className="im-dim"><span className="im-dim-l">The stone</span><div className="im-chips">{GEMS.map(f => <button key={f} className={'im-chip'+(muse.gem===f?' on':'')} onClick={()=>toggle('gem',f)}>{f}</button>)}</div></div>
            <div className="im-dim"><span className="im-dim-l">For…</span><div className="im-chips">{OCCASIONS.map(f => <button key={f} className={'im-chip'+(muse.occ===f?' on':'')} onClick={()=>toggle('occ',f)}>{f.replace(/^an? /,'')}</button>)}</div></div>
            {museHasAny && <div className="im-muse-line">Your muse: <b>{composeMuse()}</b></div>}
            <div className="im-go">
              <button className="btn btn-primary" onClick={()=>imagine(composeMuse())} disabled={phase==='thinking'}>{phase==='thinking'?'Imagining…':'✦ Imagine it'}</button>
              {museHasAny && <button className="im-ex" onClick={()=>setMuse({mood:null,era:null,gem:null,form:null,occ:null})}>clear</button>}
            </div>
          </div>
        )}

        {tab === 'stars' && (
          <div>
            <span className="im-dim-l">Pick a birth month — we’ll design around its stone</span>
            <div className="im-months" style={{marginTop:10}}>
              {MONTHS.map((mo,i) => <button key={mo[0]} className={'im-month'+(month===i?' on':'')} onClick={()=>setMonth(i)}><span className="m">{mo[0]}</span><span className="g">{mo[1]}</span></button>)}
            </div>
            <div className="im-go">
              <button className="btn btn-primary" onClick={imagineBirthstone} disabled={month===null || phase==='thinking'}>{phase==='thinking'?'Imagining…':(month!==null?('✦ Imagine my '+MONTHS[month][1]+' piece'):'Pick a month')}</button>
            </div>
          </div>
        )}

        {tab === 'words' && (
          <div>
            <textarea className="im-textarea" rows={3} maxLength={1200} value={dream}
              placeholder="A piece you saw once and never forgot… the stone, the shape, the feeling."
              onChange={e=>setDream(e.target.value)}
              onKeyDown={e=>{ if(e.key==='Enter'&&(e.metaKey||e.ctrlKey)) imagine(dream); }} />
            <div className="im-examples">{EXAMPLES.map((ex,i)=><button key={i} className="im-ex" onClick={()=>{ setDream(ex); imagine(ex); }}>{ex}</button>)}</div>
            <div className="im-go">
              <button className="btn btn-primary" onClick={()=>imagine(dream)} disabled={phase==='thinking'}>{phase==='thinking'?'Imagining…':'✦ Imagine it'}</button>
            </div>
          </div>
        )}
        {err && <p className="im-err">{err}</p>}
      </div>

      {(phase === 'thinking' || phase === 'result') && (
        <div className="im-stage">
          <div className="im-viewer">
            <div className="im-frame">
              {mainSrc && !(view==='blueprint' && wire==='loading')
                ? <img src={mainSrc} alt={concept ? concept.name : 'Your piece'} />
                : <div className="im-skel"><span className="im-spin"></span><span>{stageMsg}</span></div>}
              {hero && view==='render' && <span className="im-badge">✦ Nano Banana 2</span>}
              {hero && view==='blueprint' && <span className="im-badge">Technical blueprint</span>}
            </div>
            {hero && (
              <React.Fragment>
                <div className="im-actions" style={{justifyContent:'space-between'}}>
                  <div className="im-toggle">
                    <button className={view==='render'?'on':''} onClick={()=>setView('render')}>Render</button>
                    <button className={view==='blueprint'?'on':''} onClick={genWire}>{wire==='loading'?'Blueprint…':'Blueprint'}</button>
                  </div>
                  <div className="im-thumbs">
                    {TONES.map(t => { const val=variants[t.k]; const img=isUrl(val);
                      return <button key={t.k} className={'im-thumb'+(active===t.k&&view==='render'?' on':'')} disabled={val==='loading'} title={t.k==='original'?t.label:('Render in '+t.label.toLowerCase()+' gold')} onClick={()=>genVariant(t.k)}>
                        <span className="sw">{img ? <img src={val} alt={t.label}/> : val==='loading' ? <span className="im-spin sm"></span> : <span className="im-thumb-x">+</span>}</span>
                        <span className="tl">{t.label}</span>
                      </button>;
                    })}
                  </div>
                </div>
                <div className="im-actions">
                  {mainSrc && <a className="link-arrow" href={mainSrc} download={((concept&&concept.name)?concept.name.replace(/\s+/g,'-'):'studio76-piece')+'.png'}>Download</a>}
                  <a className="btn btn-light" href="/blueprint.html">Bring it to the bench →</a>
                </div>
              </React.Fragment>
            )}
          </div>

          <div className="im-side">
            {concept ? (
              <div className="im-concept">
                <span className="im-kicker">✦ The piece</span>
                <h3 className="im-name">{concept.name}</h3>
                {concept.description && <p className="im-desc">{concept.description}</p>}
                {concept.why_it_works && <p className="im-why"><b>Why it works</b>{concept.why_it_works}</p>}
                {(concept.price_tier || concept.indicative_range) && (
                  <div className="im-price">
                    {concept.price_tier && <span className="pill">{concept.price_tier}</span>}
                    {concept.indicative_range && <span className="im-range">{concept.indicative_range}</span>}
                  </div>
                )}
              </div>
            ) : (
              <div className="im-concept im-concept-skel"><span className="im-spin"></span><p>Composing your concept…</p></div>
            )}
            {spec && (spec.piece_type || spec.silhouette) && (
              <div className="im-spec">
                <span className="im-kicker">✦ We broke it down</span>
                <Row l="Piece" v={spec.piece_type} />
                <Row l="Silhouette" v={spec.silhouette} />
                <Row l="Hero stone" v={fmtStone(spec.hero_stone)} />
                <Row l="Accents" v={fmtAcc(spec.accent_stones)} />
                <Row l="Metal" v={spec.metal_tone} />
                <Row l="Motif" v={spec.motif} />
                <Row l="Era / mood" v={spec.era_mood} />
                <Row l="Setting" v={spec.setting_style} />
              </div>
            )}
          </div>
        </div>
      )}
    </main>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<Imaginarium />);
