/* Sections, Copy, Hub and Images pages. All edit the shared draft via useDraft(). */
const RAIL_TYPES = { rail: 'Rail', featured: 'Featured rail', promo: 'Promo block', hub: 'Collection hub', live: 'Live auctions' };
const SECTION_HINT = { intent: 'Search results grid; only when the visitor arrived with a signer or search', similar: 'Similar products under the search grid (relationships engine)', live: 'Live and scheduled auction lots', 'continue': 'Recently viewed, from first-party memory', for_you: 'Searchspring home profile', trending: 'Trending searches, one tile per query', season: 'The leading active season (Seasons page)', hub: 'Six doors into the catalog (Hub page)' };

function SectionsPage() {
  const { doc, setDoc, segments, assets, reloadAssets } = useDraft();
  const [open, setOpen] = useState(null); const [drag, setDrag] = useState(null); const [over, setOver] = useState(null); const [adding, setAdding] = useState(null);
  const sections = doc.sections || [];
  const update = (id, patch) => setDoc(d => ({ ...d, sections: d.sections.map(s => s.id === id ? { ...s, ...patch } : s) }));
  const remove = (id) => setDoc(d => ({ ...d, sections: d.sections.filter(s => s.id !== id) }));
  const reorder = (fromId, toId) => setDoc(d => {
    const list = d.sections.slice(); const fi = list.findIndex(s => s.id === fromId), ti = list.findIndex(s => s.id === toId); if (fi < 0 || ti < 0) return d;
    const [it] = list.splice(fi, 1); list.splice(ti, 0, it);
    // the order sets the base weights, so arrival boosts still apply on top
    let w = 100; return { ...d, sections: list.map(s => { if (s.locked) return s; const n = { ...s, weight: w }; w -= 3; return n; }) };
  });
  const addSection = (type) => {
    const id = `${type}_${Date.now().toString(36)}`;
    const base = { id, type, enabled: true, pinned: false, weight: 75, title: '', sub: '', more: '', why: '', tiles: 12 };
    const s = type === 'featured' ? { ...base, title: 'Featured signer', signer: '', query: {} } : { ...base, weight: 60, promo: { headline: '', body: '', link: '', cta: 'Shop now', asset_id: null } };
    setDoc(d => ({ ...d, sections: [...d.sections.slice(0, 4), s, ...d.sections.slice(4)] })); setOpen(id); setAdding(null);
  };
  return <div>
    <div className="topbar"><h1>Sections</h1><span className="muted">Drag to reorder. The order sets the base weights; arrival boosts still apply. Locked rows always lead when they apply.</span><div className="right row"><button className="btn" onClick={() => addSection('featured')}>+ Featured rail</button><button className="btn" onClick={() => addSection('promo')}>+ Promo block</button></div></div>
    {sections.map(s => <React.Fragment key={s.id}>
      <div className={'sec ' + (drag === s.id ? 'dragging' : '') + (over === s.id ? ' over' : '') + (s.enabled ? '' : ' off')} draggable={!s.locked} onDragStart={() => setDrag(s.id)} onDragOver={e => { e.preventDefault(); if (drag && drag !== s.id) setOver(s.id); }} onDragLeave={() => setOver(null)} onDrop={() => { if (drag && drag !== s.id) reorder(drag, s.id); setDrag(null); setOver(null); }} onDragEnd={() => { setDrag(null); setOver(null); }}>
        <div className="handle">{s.locked ? '🔒' : '⋮⋮'}</div>
        <Toggle on={s.enabled} onChange={v => update(s.id, { enabled: v })} />
        <div className="grow" onClick={() => setOpen(open === s.id ? null : s.id)} style={{ cursor: 'pointer' }}>
          <div className="type">{RAIL_TYPES[s.type] || s.type} · <span className="mono">{s.id}</span> · weight {s.weight}{s.pinned ? ' · pinned to top' : ''}{s.target && (s.target.show?.length || s.target.hide?.length) ? ' · targeted' : ''}</div>
          <div className="title">{s.type === 'promo' ? (s.promo?.headline || 'Untitled promo') : s.type === 'hub' ? (doc.hub?.title || 'Shop by collection') : (s.title || (s.id === 'intent' ? '“{intent}”, signed.' : s.id === 'season' ? 'Season title (from the Seasons page)' : s.id))}</div>
          <div className="sub">{s.type === 'promo' ? (s.promo?.body || '') : (s.sub || SECTION_HINT[s.id] || '')}</div>
        </div>
        <div className="row"><button className="btn sm" onClick={() => setOpen(open === s.id ? null : s.id)}>{open === s.id ? 'Close' : 'Edit'}</button></div>
      </div>
      {open === s.id && <SectionEditor s={s} update={p => update(s.id, p)} remove={() => { remove(s.id); setOpen(null); }} segments={segments} assets={assets} reloadAssets={reloadAssets} />}
    </React.Fragment>)}
  </div>;
}
function SectionEditor({ s, update, remove, segments, assets, reloadAssets }) {
  const setTarget = (k, list) => update({ target: { ...(s.target || {}), [k]: list } });
  const segOpts = (segments || []).map(x => x.key);
  return <div className="sec-edit stack">
    {s.type !== 'hub' && s.type !== 'promo' && <div className="grid3">
      <Field label="Title" count={(s.title || '').length} max={48}><Text value={s.title} onChange={v => update({ title: v })} placeholder={s.id === 'intent' ? 'Uses “{intent}”' : ''} /></Field>
      <Field label="Subtitle" count={(s.sub || '').length} max={90}><Text value={s.sub} onChange={v => update({ sub: v })} /></Field>
      <Field label="See-all link" hint="Store-relative, e.g. /signed-books/"><Text value={s.more} onChange={v => update({ more: v })} /></Field>
    </div>}
    {s.type === 'featured' && <div className="stack">
      <Field label="Signer" hint="A signer name makes a search-backed rail with the same grid and similar-products treatment. Leave empty to use the query below."><Text value={s.signer} onChange={v => update({ signer: v })} placeholder="Ozzy Osbourne" /></Field>
      {!s.signer && <Field label="Or a catalog query"><QueryBuilder value={s.query} onChange={q => update({ query: q })} /></Field>}
      {s.signer && <div className="row"><SignerProof signer={s.signer} /></div>}
    </div>}
    {s.type === 'promo' && <PromoEditor p={s.promo || {}} onChange={p => update({ promo: { ...(s.promo || {}), ...p } })} assets={assets} reloadAssets={reloadAssets} />}
    {s.type !== 'promo' && s.type !== 'hub' && s.type !== 'live' && <div className="grid3">
      <Field label="Why this rail" hint="One line under personalized rails. {intent} is replaced." count={(s.why || '').length} max={80}><Text value={s.why} onChange={v => update({ why: v })} /></Field>
      <Field label="Tiles"><input type="number" min="4" max="24" value={s.tiles || 12} onChange={e => update({ tiles: Number(e.target.value) })} /></Field>
      <Field label={`Base weight: ${s.weight}`} hint="Higher shows earlier. Arrival boosts add to this."><input type="range" min="10" max="100" value={s.weight} onChange={e => update({ weight: Number(e.target.value) })} disabled={s.locked} /></Field>
    </div>}
    <div className="row wrap">
      <Toggle on={s.pinned} onChange={v => update({ pinned: v })} label="Pin to top" />
      <span className="muted small">Show only to:</span><SegPicker options={segOpts} value={s.target?.show || []} onChange={l => setTarget('show', l)} />
      <span className="muted small">Hide from:</span><SegPicker options={segOpts} value={s.target?.hide || []} onChange={l => setTarget('hide', l)} />
    </div>
    {segOpts.length > 0 && s.type !== 'promo' && s.type !== 'hub' && <Field label="Title by segment" hint="Optional: a different title for a segment"><div className="grid3">{segOpts.map(k => <div className="row" key={k}><span className="pill">{k}</span><input type="text" value={(s.titles_by_segment || {})[k] || ''} onChange={e => update({ titles_by_segment: { ...(s.titles_by_segment || {}), [k]: e.target.value } })} /></div>)}</div></Field>}
    <div className="row"><span className="muted small">Min app version for this type: {useDraft().doc.min_app_version?.[s.type] || '—'}</span>{(s.type === 'featured' || s.type === 'promo') && <button className="btn sm danger right" onClick={remove}>Remove section</button>}</div>
  </div>;
}
function SignerProof({ signer }) {
  const [r, setR] = useState(null);
  useDebouncedEffect(async () => { const x = await api('/seasons/proof', { method: 'POST', body: { signer } }); setR(x.data || null); }, [signer], 500);
  if (!r) return <span className="muted small">Checking…</span>;
  return <span className={'pill ' + (r.total < 4 ? 'bad' : r.total < 8 ? 'warn' : 'good')}>{fmt(r.total)} in stock for “{signer}”</span>;
}
function SegPicker({ options, value, onChange }) {
  return <select value="" onChange={e => { if (e.target.value && !value.includes(e.target.value)) onChange([...value, e.target.value]); }} style={{ width: 'auto' }}>
    <option value="">{value.length ? value.join(', ') : 'everyone'}</option>{options.map(o => <option key={o} value={o}>{o}</option>)}{value.length > 0 && <option value="">— clear —</option>}
  </select>;
}
function PromoEditor({ p, onChange, assets, reloadAssets }) {
  return <div className="stack">
    <div className="grid2"><Field label="Headline" count={(p.headline || '').length} max={60}><Text value={p.headline} onChange={v => onChange({ headline: v })} /></Field><Field label="Button text" count={(p.cta || '').length} max={24}><Text value={p.cta} onChange={v => onChange({ cta: v })} /></Field></div>
    <Field label="Body" count={(p.body || '').length} max={160}><textarea value={p.body || ''} onChange={e => onChange({ body: e.target.value })} /></Field>
    <div className="grid2"><Field label="Link" hint="Store-relative or full URL"><Text value={p.link} onChange={v => onChange({ link: v })} /></Field><Field label="Image" hint="Replaces the Page Builder region art"><AssetPicker value={p.asset_id} onChange={v => onChange({ asset_id: v })} assets={assets} reload={reloadAssets} /></Field></div>
  </div>;
}

/* ------------------------------------------------------------------ Copy */
function CopyPage() {
  const { doc, setDoc, assets, reloadAssets } = useDraft();
  const hero = doc.hero || {}; const [tab, setTab] = useState('default');
  const setHero = (k, patch) => setDoc(d => ({ ...d, hero: { ...(d.hero || {}), [k]: { ...((d.hero || {})[k] || {}), ...patch } } }));
  const h = hero[tab] || {};
  const VARIANTS = [['default', 'Default'], ['returning', 'Returning'], ['social', 'Social'], ['email', 'Email'], ['member', 'Member'], ['live', 'Auction week'], ['intent', 'Search intent']];
  const setList = (key, i, patch) => setDoc(d => ({ ...d, [key]: (d[key] || []).map((x, k) => k === i ? (typeof x === 'string' ? patch : { ...x, ...patch }) : x) }));
  return <div>
    <div className="topbar"><h1>Copy</h1><span className="muted">Hero per arrival, trust items, proof line, SEO block, FAQ. Placeholders: {'{first}'}, {'{intent}'}.</span></div>
    <div className="card"><h2>Hero</h2>
      <div className="tabs row wrap" style={{ marginBottom: 12 }}>{VARIANTS.map(([k, l]) => <button key={k} className={'tab ' + (tab === k ? 'active' : '')} onClick={() => setTab(k)}>{l}</button>)}</div>
      <div className="split">
        <div className="stack">
          <Field label="Kicker" count={(h.kicker || '').length} max={48}><Text value={h.kicker} onChange={v => setHero(tab, { kicker: v })} /></Field>
          <Field label="Title" hint="Empty keeps the server-rendered H1. <em> allowed." count={(h.title || '').length} max={60}><Text value={h.title} onChange={v => setHero(tab, { title: v })} /></Field>
          <Field label="Subtitle" count={(h.sub || '').length} max={180}><textarea value={h.sub || ''} onChange={e => setHero(tab, { sub: e.target.value })} /></Field>
          {tab === 'returning' && <Field label="Subtitle when lots are live" count={(h.sub_live || '').length} max={180}><textarea value={h.sub_live || ''} onChange={e => setHero(tab, { sub_live: e.target.value })} /></Field>}
          {tab === 'intent' && <>
            <Field label="Kicker · social arrival"><Text value={h.social_kicker} onChange={v => setHero(tab, { social_kicker: v })} /></Field><Field label="Subtitle · social arrival"><textarea value={h.social_sub || ''} onChange={e => setHero(tab, { social_sub: e.target.value })} /></Field>
            <Field label="Kicker · email arrival"><Text value={h.email_kicker} onChange={v => setHero(tab, { email_kicker: v })} /></Field><Field label="Subtitle · email arrival"><textarea value={h.email_sub || ''} onChange={e => setHero(tab, { email_sub: e.target.value })} /></Field>
          </>}
          <Field label="Hero art override" hint="Optional. Replaces the product mosaic for this arrival."><AssetPicker value={h.asset_id} onChange={v => setHero(tab, { asset_id: v })} assets={assets} reload={reloadAssets} /></Field>
        </div>
        <div><div className="muted small" style={{ marginBottom: 6 }}>How it wraps on a phone</div><PhonePreview kicker={(h.kicker || '').replace('{first}', 'Sam').replace('{intent}', 'Ozzy Osbourne')} title={(h.title || '').replace('{intent}', 'Ozzy Osbourne')} sub={(h.sub || '').replace('{first}', 'Sam').replace(/\{intent\}/g, 'Ozzy Osbourne')} /></div>
      </div>
    </div>
    <div className="card"><h2>Proof line</h2><div className="grid3">{(doc.proof || []).map((p, i) => <Field key={i} label={`Item ${i + 1}`} count={p.length} max={28}><Text value={p} onChange={v => setList('proof', i, v)} /></Field>)}</div></div>
    <div className="card"><h2>Trust band</h2><div className="grid2">{(doc.trust || []).map((t, i) => <div className="stack" key={i}><Field label={`Title ${i + 1}`} count={(t.title || '').length} max={28}><Text value={t.title} onChange={v => setList('trust', i, { title: v })} /></Field><Field label="Body" count={(t.body || '').length} max={120}><textarea value={t.body || ''} onChange={e => setList('trust', i, { body: e.target.value })} /></Field></div>)}</div></div>
    <div className="card"><h2>SEO block</h2><div className="stack">
      <Field label="Heading" count={(doc.seo?.title || '').length} max={80}><Text value={doc.seo?.title} onChange={v => setDoc(d => ({ ...d, seo: { ...(d.seo || {}), title: v } }))} /></Field>
      {(doc.seo?.paragraphs || []).map((p, i) => <Field key={i} label={`Paragraph ${i + 1}`} hint="Plain text. The category links are added by the theme." count={p.length}><textarea value={p} onChange={e => setDoc(d => ({ ...d, seo: { ...(d.seo || {}), paragraphs: d.seo.paragraphs.map((x, k) => k === i ? e.target.value : x) } }))} /></Field>)}
      <div className="row"><button className="btn sm" onClick={() => setDoc(d => ({ ...d, seo: { ...(d.seo || {}), paragraphs: [...(d.seo?.paragraphs || []), ''] } }))}>+ Paragraph</button>{(doc.seo?.paragraphs || []).length > 1 && <button className="btn sm" onClick={() => setDoc(d => ({ ...d, seo: { ...d.seo, paragraphs: d.seo.paragraphs.slice(0, -1) } }))}>Remove last</button>}</div>
    </div></div>
    <div className="card"><h2>FAQ</h2><span className="muted small">Rendered with FAQ structured data under the SEO block. Leave empty to hide.</span>
      <div className="stack" style={{ marginTop: 10 }}>{(doc.faq || []).map((f, i) => <div className="grid2" key={i}><Field label="Question"><Text value={f.q} onChange={v => setList('faq', i, { q: v })} /></Field><Field label="Answer"><textarea value={f.a || ''} onChange={e => setList('faq', i, { a: e.target.value })} /></Field></div>)}
        <div className="row"><button className="btn sm" onClick={() => setDoc(d => ({ ...d, faq: [...(d.faq || []), { q: '', a: '' }] }))}>+ Question</button>{(doc.faq || []).length > 0 && <button className="btn sm" onClick={() => setDoc(d => ({ ...d, faq: d.faq.slice(0, -1) }))}>Remove last</button>}</div></div></div>
    <div className="card"><h2>Storefront features</h2><div className="grid3">
      <Field label="Free shipping bar" hint="Threshold in dollars; 0 hides the bar"><div className="row"><Toggle on={doc.shipping?.bar} onChange={v => setDoc(d => ({ ...d, shipping: { ...(d.shipping || {}), bar: v } }))} /><input type="number" value={doc.shipping?.free_threshold || 0} onChange={e => setDoc(d => ({ ...d, shipping: { ...(d.shipping || {}), free_threshold: Number(e.target.value) } }))} /></div></Field>
      <Field label="Search rescue + notify me"><div className="stack"><Toggle on={doc.search?.rescue !== false} onChange={v => setDoc(d => ({ ...d, search: { ...(d.search || {}), rescue: v } }))} label="Zero-result rescue" /><Toggle on={doc.search?.notify !== false} onChange={v => setDoc(d => ({ ...d, search: { ...(d.search || {}), notify: v } }))} label="“Tell me when we get it” capture" /></div></Field>
      <Field label="Save for later"><Toggle on={doc.save_for_later !== false} onChange={v => setDoc(d => ({ ...d, save_for_later: v }))} label="Heart on tiles + saved rail" /></Field>
    </div></div>
    <div className="card"><h2>Minimum app version per section type</h2><span className="muted small">The mobile app skips a section type when its version is older than this, instead of forcing an app release.</span><div className="grid4" style={{ marginTop: 10 }}>{Object.entries(doc.min_app_version || {}).map(([k, v]) => <Field key={k} label={k}><Text value={v} onChange={val => setDoc(d => ({ ...d, min_app_version: { ...(d.min_app_version || {}), [k]: val } }))} /></Field>)}</div></div>
  </div>;
}

/* ------------------------------------------------------------------ Hub */
function HubPage() {
  const { doc, setDoc, assets, reloadAssets } = useDraft();
  const hub = doc.hub || { doors: [], links: [] };
  const setHub = (patch) => setDoc(d => ({ ...d, hub: { ...(d.hub || {}), ...patch } }));
  const setDoor = (i, patch) => setHub({ doors: hub.doors.map((x, k) => k === i ? { ...x, ...patch } : x) });
  return <div>
    <div className="topbar"><h1>Collection hub</h1><span className="muted">Six doors. The query feeds the art and the live count; the link is where the door goes.</span></div>
    <div className="card"><div className="grid2"><Field label="Title" count={(hub.title || '').length} max={40}><Text value={hub.title} onChange={v => setHub({ title: v })} /></Field><Field label="Subtitle" count={(hub.sub || '').length} max={80}><Text value={hub.sub} onChange={v => setHub({ sub: v })} /></Field></div></div>
    {hub.doors.map((d, i) => <div className="card" key={d.key || i}><div className="grid4">
      <Field label={`Door ${i + 1} label`} count={(d.label || '').length} max={22}><Text value={d.label} onChange={v => setDoor(i, { label: v })} /></Field>
      <Field label="Small line" count={(d.small || '').length} max={40}><Text value={d.small} onChange={v => setDoor(i, { small: v })} /></Field>
      <Field label="Link"><Text value={d.href} onChange={v => setDoor(i, { href: v })} /></Field>
      <Field label="Art override"><AssetPicker value={d.asset_id} onChange={v => setDoor(i, { asset_id: v })} assets={assets} reload={reloadAssets} /></Field>
    </div><div style={{ marginTop: 10 }}><Field label="Catalog query (art + count)"><QueryBuilder value={d.query} onChange={q => setDoor(i, { query: q })} /></Field></div></div>)}
    <div className="card"><h2>Links under the hub</h2><div className="stack">{(hub.links || []).map((l, i) => <div className="row" key={i}><input type="text" value={l.label} onChange={e => setHub({ links: hub.links.map((x, k) => k === i ? { ...x, label: e.target.value } : x) })} placeholder="Label" /><input type="text" value={l.href} onChange={e => setHub({ links: hub.links.map((x, k) => k === i ? { ...x, href: e.target.value } : x) })} placeholder="/path/" /><button className="btn sm" onClick={() => setHub({ links: hub.links.filter((x, k) => k !== i) })}>Remove</button></div>)}<div><button className="btn sm" onClick={() => setHub({ links: [...(hub.links || []), { label: '', href: '' }] })}>+ Link</button></div></div></div>
  </div>;
}

/* ------------------------------------------------------------------ Images */
function ImagesPage() {
  const { assets, reloadAssets } = useDraft();
  return <div><div className="topbar"><h1>Images</h1><span className="muted">Used by promo blocks, hero art and hub art overrides. Click an image to set its focal point.</span></div><div className="card"><AssetGrid assets={assets} reload={reloadAssets} /></div></div>;
}
