/* Studio 76 — The Stylist. Upload an outfit → AI styles the jewellery that completes it.
   Add your own instructions, render the ones you love, then see them on you.
   Talks only to blueprint.php (style → style_render). */

async function api(action, payload) {
  const r = await fetch('blueprint.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 downscale(file, max) {
  return new Promise((res, rej) => {
    const fr = new FileReader();
    fr.onerror = () => rej(new Error('read'));
    fr.onload = () => { const img = new Image();
      img.onload = () => { const s = Math.min(1, max / Math.max(img.width, img.height));
        const w = Math.round(img.width * s), h = Math.round(img.height * s);
        const c = document.createElement('canvas'); c.width = w; c.height = h;
        c.getContext('2d').drawImage(img, 0, 0, w, h); res(c.toDataURL('image/jpeg', 0.86)); };
      img.onerror = () => rej(new Error('img')); img.src = fr.result; };
    fr.readAsDataURL(file);
  });
}
const isUrl = x => typeof x === 'string' && x.slice(0, 5) === 'data:';

function Stylist() {
  const [stage, setStage] = React.useState('idle');   // idle | analyzing | ready
  const [src, setSrc]     = React.useState(null);
  const [id, setId]       = React.useState(null);
  const [outfit, setOutfit] = React.useState(null);
  const [picks, setPicks] = React.useState([]);
  const [renders, setRenders] = React.useState({});    // index → dataUrl | 'loading'
  const [instr, setInstr] = React.useState('');
  const [urlText, setUrlText] = React.useState('');
  const [drag, setDrag]   = React.useState(false);
  const [modal, setModal] = React.useState('');
  const [err, setErr]     = React.useState('');
  const fileRef = React.useRef(null);

  async function handleFile(file) {
    if (!file || !/^image\//.test(file.type)) { setErr('Please choose an image file.'); return; }
    setErr(''); setStage('analyzing'); setOutfit(null); setPicks([]); setRenders({}); setId(null);
    try {
      const d = await downscale(file, 1280); setSrc(d);
      const j = await api('style', { image: d, instructions: instr });
      setId(j.id); setOutfit(j.outfit); setPicks(j.picks || []); setStage('ready');
    } catch (e) { setErr(e.message || 'Could not read that outfit.'); setStage('idle'); }
  }
  async function handleUrl(url) {
    url = (url || '').trim();
    if (!/^https?:\/\//i.test(url)) { setErr('Paste a valid image URL.'); return; }
    setErr(''); setStage('analyzing'); setOutfit(null); setPicks([]); setRenders({}); setId(null); setSrc(url);
    try { const j = await api('style', { imageUrl: url, instructions: instr }); setId(j.id); setOutfit(j.outfit); setPicks(j.picks || []); setStage('ready'); }
    catch (e) { setErr(e.message || 'Could not bring that in.'); setStage('idle'); }
  }

  function renderPick(i) {
    if (!id || renders[i] === 'loading') return;
    setRenders(r => Object.assign({}, r, { [i]: 'loading' }));
    api('style_render', { id, pick: picks[i], instructions: instr })
      .then(j => setRenders(r => Object.assign({}, r, { [i]: j.dataUrl })))
      .catch(e => { setRenders(r => { const n = Object.assign({}, r); delete n[i]; return n; }); setErr(e.message || 'Render failed.'); });
  }
  function renderAll() { picks.forEach((p, i) => { if (!renders[i]) renderPick(i); }); }

  function tryOn(dataUrl) {
    try { sessionStorage.setItem('s76_piece', dataUrl); } catch (e) {}
    window.location.href = '/tryiton.html';
  }
  function reset() { setStage('idle'); setSrc(null); setId(null); setOutfit(null); setPicks([]); setRenders({}); setErr(''); }

  const Row = ({ l, v }) => v ? <div className="sy-row"><span className="sy-k">{l}</span><span className="sy-v">{v}</span></div> : null;

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

      <section className="sy-hero">
        <h1 className="sy-title">Style the <span className="it">whole look.</span></h1>
        <p className="sy-sub">Show us what you’re wearing — a dress, a saree, a whole outfit — and we’ll style the jewellery that completes it. Render the pieces you love, then see them on you.</p>
      </section>

      {err && <p className="sy-err">{err}</p>}

      {stage === 'idle' && (
        <React.Fragment>
          <div className={'sy-drop' + (drag ? ' over' : '')}
            onClick={() => fileRef.current && fileRef.current.click()}
            onDragOver={e => { e.preventDefault(); setDrag(true); }}
            onDragLeave={() => setDrag(false)}
            onDrop={e => { e.preventDefault(); setDrag(false); handleFile(e.dataTransfer.files[0]); }}>
            <div className="sy-drop-icon">
              <svg viewBox="0 0 24 24" width="32" height="32" fill="none"><path d="M12 16V5m0 0L8 9m4-4 4 4" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/><path d="M4 15v3a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-3" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/></svg>
            </div>
            <p className="sy-drop-t">Drop your outfit photo, or <span>browse</span></p>
            <p className="sy-drop-s">A clear, well-lit shot of the look — on you or laid out — works best.</p>
            <input ref={fileRef} type="file" accept="image/*" hidden onChange={e => handleFile(e.target.files[0])} />
          </div>
          <div className="sy-instr">
            <input className="sy-input" value={instr} maxLength={400}
              placeholder="Any preferences? e.g. emeralds, statement pieces, yellow gold only, keep it minimal…"
              onChange={e => setInstr(e.target.value)} />
          </div>
          <p className="sy-instr-hint">Optional — your instructions guide what we recommend &amp; how it’s rendered.</p>
          <div className="sy-paste">
            <input className="sy-input" value={urlText} placeholder="…or paste an outfit image URL"
              onChange={e => setUrlText(e.target.value)} onKeyDown={e => { if (e.key === 'Enter') handleUrl(urlText); }} />
            <button className="sy-tryon" disabled={!urlText.trim()} onClick={() => handleUrl(urlText)} style={{padding:'12px 18px'}}>Bring it in</button>
          </div>
        </React.Fragment>
      )}

      {stage === 'analyzing' && (
        <div className="sy-drop"><div className="sy-pick-empty"><span className="sy-spin"></span><span>Styling your look…</span></div></div>
      )}

      {stage === 'ready' && (
        <div className="sy-stage">
          <aside className="sy-left">
            <div className="sy-orig">{src ? <img src={src} alt="Your outfit" /> : null}<button className="sy-redo" onClick={reset}>New outfit</button></div>
            {outfit && (
              <div className="sy-read">
                <span className="sy-read-k">✦ The read</span>
                <p className="sy-read-sum">{outfit.summary}</p>
                <Row l="Palette" v={outfit.palette} />
                <Row l="Occasion" v={outfit.occasion} />
                <Row l="Neckline" v={outfit.neckline && outfit.neckline.toLowerCase() !== 'n/a' ? outfit.neckline : ''} />
                <Row l="Best metal" v={outfit.metal} />
              </div>
            )}
            <div className="sy-instr" style={{margin:0}}>
              <input className="sy-input" value={instr} maxLength={400}
                placeholder="Tweak the brief — e.g. only emeralds, bolder…"
                onChange={e => setInstr(e.target.value)} />
            </div>
            <p className="sy-instr-hint" style={{margin:0}}>Edit, then re-render any piece to apply.</p>
          </aside>

          <div className="sy-right">
            <div className="sy-right-h">
              <span className="sy-right-t">Styled for your look</span>
              {picks.length > 0 && <button className="sy-dl" style={{background:'none',border:'none',cursor:'pointer'}} onClick={renderAll}>Render all ↻</button>}
            </div>
            <div className="sy-grid">
              {picks.map((p, i) => {
                const r = renders[i];
                return (
                  <div className="sy-pick" key={i}>
                    <div className="sy-pick-media">
                      <span className="sy-pick-cat">{p.type}</span>
                      {isUrl(r)
                        ? <img src={r} alt={p.name} onClick={() => setModal(r)} />
                        : r === 'loading'
                          ? <div className="sy-pick-empty"><span className="sy-spin"></span><span>Rendering…</span></div>
                          : <div className="sy-pick-empty"><button className="sy-render-btn" onClick={() => renderPick(i)}>✦ Render it</button></div>}
                    </div>
                    <div className="sy-pick-body">
                      <span className="sy-pick-name">{p.name}</span>
                      <span className="sy-pick-meta">{[p.style, p.metal, p.stones].filter(Boolean).join(' · ')}</span>
                      {p.why && <span className="sy-pick-why">“{p.why}”</span>}
                      {isUrl(r) && (
                        <div className="sy-pick-foot">
                          <a className="sy-dl" href={r} download={'studio76-' + (p.name || 'piece').replace(/\s+/g,'-') + '.png'}>Download</a>
                          <button className="sy-tryon" onClick={() => tryOn(r)}>See it on you →</button>
                        </div>
                      )}
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        </div>
      )}

      <div className={'sy-modal' + (modal ? ' on' : '')} onClick={() => setModal('')}>
        <span className="sy-modal-x">×</span>
        {modal && <img src={modal} alt="" onClick={e => e.stopPropagation()} />}
      </div>
    </main>
  );
}

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