// ─── Expanded in-page content for a listing ───
// Per-asset billing pill — what the client actually pays for each deliverable.
const BILL = { paid: ['$50', 'paid'], free: ['Free', 'free'], shared: ['Shared', 'shared'], incl: ['Included', 'incl'], video: ['$400', 'paid'] };
function BillPill({ d }) {
  if (d.bill === 'aplus') return <span className="bill paid" title={d.billNote || 'A+ modules billed per image'}>{money(d.price)}</span>;
  const e = BILL[d.bill];
  if (!e) return null;
  const [label, cls] = e;
  const title =
    d.bill === 'shared' ? `Shared from the original creation${d.sharedFrom ? ` (${d.sharedFrom.toUpperCase()})` : ''} — created once, not billed again`
    : d.bill === 'free' ? 'Included free — not billed'
    : d.bill === 'incl' ? 'Bundled with the package — no extra charge'
    : undefined;
  return <span className={`bill ${cls}`} title={title}>{label}</span>;
}

function DCard({ d, onZoom }) {
  return (
    <article className={`dcard ${d.tall ? 'tall' : ''}`}>
      <div className="thumb" onClick={() => d.loadable && onZoom()} style={{ cursor: d.loadable ? 'zoom-in' : 'default' }}>
        {d.loadable
          ? <img src={d.url} alt={d.name} loading="lazy"/>
          : <Placeholder label={d.tall ? 'Preview rendering' : 'In production'} glyph={d.tall ? 'layers' : 'image'}/>}
      </div>
      <div className="di">
        <div className="dn">{d.name}{d.sub && !d.name.includes(d.sub) ? ` · ${d.sub}` : ''}<BillPill d={d}/></div>
        <div className="dd">{d.desc}</div>
      </div>
    </article>
  );
}

function VideoCard({ d, accent }) {
  const dur = (d.sub || '').match(/(\d+)\s*s/);
  const ref = useRef(null);
  const [on, setOn] = useState(false);
  const playable = d.loadable && d.url;
  const start = () => { const v = ref.current; if (v) { v.play().catch(() => {}); } };
  return (
    <article className="vcard">
      <div className={`vstage${playable ? ' has-vid' : ''}`} style={{ '--accent': accent }}>
        {playable && (
          <video ref={ref} className="vvid" src={d.url + '#t=0.1'} poster={d.poster || undefined}
            preload="metadata" playsInline controls={on}
            onPlay={() => setOn(true)} onPause={() => setOn(false)} onEnded={() => setOn(false)}/>
        )}
        {!on && (
          playable
            ? <button type="button" className="play" onClick={start} aria-label={`Play ${d.sub || 'film'}`}><Ico d="play" size={24} fill/></button>
            : <div className="play is-soon" title="Final cut uploading"><Ico d="play" size={24} fill/></div>
        )}
        {dur && !on && <span className="vdur">{dur[1]}s</span>}
      </div>
      <div className="vi">
        <div className="vn">{d.sub || 'Hero film'}<BillPill d={d}/></div>
        <div className="vd">{d.desc}</div>
      </div>
    </article>
  );
}

function SectionHead({ title, count }) {
  return (
    <div className="dsec-head">
      <h2>{title}</h2>
      <span className="ct">{count}</span>
      <span className="rule"></span>
    </div>
  );
}

// Performance baseline — current creative's KPIs (ad CTR from BigQuery, conversion from the Business Report).
const shortN = (n) => n >= 1e6 ? (n / 1e6).toFixed(1).replace(/\.0$/, '') + 'M' : n >= 1000 ? (n / 1000).toFixed(n >= 1e5 ? 0 : 1).replace(/\.0$/, '') + 'k' : '' + n;
// Traffic-light rating vs Amazon benchmark. CTR: <0.30 poor / <0.50 okay / else great. Conv: <15 / <30 / else great.
const RATE_LABEL = { poor: 'Poor', okay: 'Okay', good: 'Great' };
const rate = (v, kind) => v == null ? null : v < (kind === 'ctr' ? 0.30 : 15) ? 'poor' : v < (kind === 'ctr' ? 0.50 : 30) ? 'okay' : 'good';
function PerfBaseline({ m }) {
  if (!m) return null;
  const ctrR = rate(m.adCtr, 'ctr'), convR = rate(m.conv, 'conv');
  return (
    <section className="pm">
      <div className="pm-head">
        <span className="pm-title">Performance baseline</span>
        <span className="pm-meta">current creative · {m.period}</span>
      </div>
      <div className="pm-row">
        <div className="pm-cell">
          <div className="pm-l">Ad CTR</div>
          <div className={`pm-v ${ctrR || ''}`} title={m.adImpr ? `${m.adImpr.toLocaleString()} Sponsored Products impressions · <0.30% poor / 0.30–0.50% okay / >0.50% great` : ''}>
            {m.adCtr != null ? m.adCtr.toFixed(2) + '%' : '—'}{ctrR && <span className="pm-tag">{RATE_LABEL[ctrR]}</span>}
          </div>
          <div className="pm-s">main image</div>
        </div>
        <div className="pm-cell">
          <div className="pm-l">Conversion</div>
          <div className={`pm-v ${convR || ''}`} title="<15% poor / 15–30% okay / >30% great">
            {m.conv != null ? m.conv.toFixed(1) + '%' : '—'}{convR && <span className="pm-tag">{RATE_LABEL[convR]}</span>}
          </div>
          <div className="pm-s">gallery · A+</div>
        </div>
        <div className="pm-cell">
          <div className="pm-l">Sessions</div>
          <div className="pm-v">{shortN(m.sessions)}</div>
          <div className="pm-s">90-day</div>
        </div>
        <div className="pm-cell">
          <div className="pm-l">Sales</div>
          <div className="pm-v">{compactMoney(m.sales)}</div>
          <div className="pm-s">90-day</div>
        </div>
      </div>
    </section>
  );
}

// Designer (Upwork) work — an alternate take (ready listing) or a proposal (pending listing).
function DesignerWork({ work, openLightbox }) {
  const items = work.images.map((url, i) => ({ url, name: `${work.designer} · ${work.source} · ${i + 1} / ${work.images.length}`, loadable: true }));
  return (
    <section className="dsec dwork">
      <div className="dsec-head">
        <h2>{work.kind === 'alternate' ? 'Alternate take' : 'Designer proposal'}</h2>
        <span className="dwho"><span className="dwav"><img src={`assets/designers/${work.who}.png`} alt={work.designer}/></span>{work.designer} · {work.source}</span>
        <span className="rule"></span>
      </div>
      {work.note && <div className="dwork-note"><Ico d="clock" size={12} sw={1.8}/>{work.note}</div>}
      <div className="dwork-grid">
        {items.map((d, i) => (
          <button className="dwork-thumb" key={i} onClick={() => openLightbox(items, i)} title={`View ${i + 1} of ${items.length}`}>
            <img src={d.url} loading="lazy" alt={d.name}/>
          </button>
        ))}
      </div>
    </section>
  );
}

function ExpandedContent({ L, openLightbox }) {
  const images = L.deliverables.filter(d => d.kind === 'image');
  const videos = L.deliverables.filter(d => d.kind === 'video');
  const aplus  = L.deliverables.filter(d => d.kind === 'aplus');
  const imgLoadable = images.filter(d => d.loadable);
  const aplusLoadable = aplus.filter(d => d.loadable);

  return (
    <div className="exp-pad" style={{ '--accent': L.accent }}>
      <div className="xhead">
        <div className="xh-fact">
          <div className="xh-eyebrow">Formulation</div>
          <div className="xh-val">{L.tag}</div>
          {L.compareTo && <div className="xh-vs">vs <strong>{L.compareTo}</strong>{L.asin ? ` · ${L.asin}` : ''}</div>}
        </div>
        {L.benchmark ? (
          <div className="xh-fact end">
            <div className="xh-eyebrow">Category incumbent</div>
            <div className="xh-val">{compactMoney(L.benchmark.revenue)}<span className="xh-u"> / mo</span></div>
            <div className="xh-vs">{L.benchmark.units.toLocaleString()} units / mo</div>
          </div>
        ) : (
          <div className="xh-fact end">
            <div className="xh-eyebrow">Category</div>
            <div className="xh-vs" style={{ maxWidth: 240, marginTop: 5 }}>New entry — creative built to establish the {L.short} shelf.</div>
          </div>
        )}
      </div>

      {L.metrics && <PerfBaseline m={L.metrics} accent={L.accent}/>}

      <section className="dsec" style={{ marginTop: 26 }}>
        <SectionHead title="Listing gallery" count={`${images.length} images`}/>
        <div className="dgrid">
          {images.map((d, i) => (
            <DCard key={i} d={d} onZoom={() => openLightbox(imgLoadable, imgLoadable.findIndex(x => x === d))}/>
          ))}
        </div>
      </section>

      {videos.length > 0 && (
        <section className="dsec">
          <SectionHead title="Hero video" count={`${videos.length} ${videos.length > 1 ? 'films' : 'film'}`}/>
          <div className="dgrid" style={{ gridTemplateColumns: 'repeat(auto-fill,minmax(360px,1fr))' }}>
            {videos.map((d, i) => <VideoCard key={i} d={d} accent={L.accent}/>)}
          </div>
        </section>
      )}

      {aplus.length > 0 && (
        <section className="dsec">
          <SectionHead title="A+ content" count="Full-flow preview"/>
          <div className="dgrid" style={{ gridTemplateColumns: 'repeat(auto-fill,minmax(300px,1fr))', alignItems: 'start' }}>
            {aplus.map((d, i) => (
              <DCard key={i} d={d} onZoom={() => openLightbox(aplusLoadable, aplusLoadable.findIndex(x => x === d))}/>
            ))}
          </div>
        </section>
      )}

      {L.designerWork && <DesignerWork work={L.designerWork} openLightbox={openLightbox}/>}
    </div>
  );
}

const STUDIO = [
  { id: 'shaikh', name: 'Shaikh', full: 'Shaikh Mohteshim', img: 'assets/designers/shaikh.png', set: 200, aplus: 200 },
  { id: 'awais', name: 'Awais', full: 'Muhammad Awais', img: 'assets/designers/awais.png', set: 200, aplus: 300 },
  { id: 'kateryna', name: 'Kateryna', full: 'Kateryna Tereshchenko', img: 'assets/designers/kateryna.png', set: 300, aplus: 450, note: '+$20 PSD · +$10/image' },
];
const AI_RATE = { set: 250, aplus: 250, video: 400, pkg: 900 };
const ALEKS_VIDEO = 1000;

function PendingPanel({ L, started, onStart, openLightbox }) {
  const [pick, setPick] = useState(L.designerWork?.who || 'shaikh');
  const sel = STUDIO.find(d => d.id === pick);
  const q = L.quote || { paid: 6, free: 0, sharedFrom: null, video: 0 };
  const aiSet = q.paid * 50;                            // only NEW images are billed ($50 each)
  const aiTotal = aiSet + AI_RATE.aplus + AI_RATE.video;
  const studioTotal = sel.set + sel.aplus + ALEKS_VIDEO;
  const save = studioTotal - aiTotal;
  const INCLUDED = [
    ['image', 'Main image'], ['image', 'Drug Facts'], ['image', 'Lifestyle'],
    ['image', 'Comparison'], ['layers', 'A+ content'], ['video', 'Hero video'],
  ];
  return (
    <div className="exp-pad pend-pad" style={{ '--accent': L.accent }}>
      {started ? (
        <div className="prod-state">
          <div className="prod-spin"></div>
          <div className="prod-copy">
            <h3>In production — ready in 24–48 hours</h3>
            <p>Your {L.brand} {L.short} package is rendering now. The full set — images, A+ and hero video — will appear here for review within 24–48 hours. No action needed.</p>
            <div className="prod-bar"><div className="pf"></div></div>
          </div>
        </div>
      ) : (
        <>
          {L.metrics && <PerfBaseline m={L.metrics} accent={L.accent}/>}
          {L.designerWork && <DesignerWork work={L.designerWork} openLightbox={openLightbox}/>}
          <div className="pp-head">
            <div className="pp-copy">
              <div className="eyebrow" style={{ color: L.accent }}>Self-serve · No brief needed</div>
              <h3>Generate the full {L.short} package</h3>
              <p>We already have your product data, label and brand templates loaded — no information required. Start it and the complete set is rendered for review in 24–48 hours.</p>
            </div>
            <div className="incl">
              {INCLUDED.map(([ic, label], i) => (
                <span className="ichip" key={i}><Ico d={ic} size={13} sw={1.8}/>{label}</span>
              ))}
            </div>
          </div>

          <div className="vs">
            <div className="vs-head">
              <span className="vs-title">What this would cost</span>
              <div className="vs-pick">
                <span className="vs-pick-l">vs studio:</span>
                {STUDIO.map(d => (
                  <button key={d.id} className={`pick ${pick === d.id ? 'on' : ''}`} onClick={() => setPick(d.id)} title={d.full}>
                    <span className="pick-av"><img src={d.img} alt={d.full}/></span>{d.name}
                  </button>
                ))}
              </div>
            </div>
            <div className="vs-cards">
              <div className="vs-card ai">
                <div className="vsc-top"><span className="vsc-name">Self-serve AI</span><span className="vsc-tag">Recommended</span></div>
                <div className="vsc-rows">
                  <div className="vsc-r"><span>{q.paid} new image{q.paid === 1 ? '' : 's'} × $50</span><b>{money(aiSet)}</b></div>
                  {q.free > 0 && <div className="vsc-r"><span>{q.free} {q.sharedFrom ? `shared · ${q.sharedFrom.toUpperCase()}` : 'free (FSA / claims)'}</span><b style={{ color: '#197a45' }}>Free</b></div>}
                  <div className="vsc-r"><span>Premium A+ content</span><b>{money(AI_RATE.aplus)}</b></div>
                  <div className="vsc-r"><span>Hero video</span><b>{money(AI_RATE.video)}</b></div>
                </div>
                <div className="vsc-total"><span>Full package</span><b>{money(aiTotal)}</b></div>
                <div className="vsc-eta ready"><Ico d="clock" size={12} sw={1.8}/>24–48h, every time</div>
              </div>
              <div className="vs-card studio">
                <div className="vsc-top"><span className="vsc-name">{sel.name} + Aleksandar</span></div>
                <div className="vsc-rows">
                  <div className="vsc-r"><span>Listing set</span><b>{money(sel.set)}</b></div>
                  <div className="vsc-r"><span>A+ content</span><b>{money(sel.aplus)}</b></div>
                  <div className="vsc-r"><span>Hero video</span><b>{money(ALEKS_VIDEO)}</b></div>
                </div>
                <div className="vsc-total"><span>Full package</span><b>{money(studioTotal)}</b></div>
                <div className="vsc-eta muted"><Ico d="clock" size={12} sw={1.8}/>By availability{sel.note ? ` · ${sel.note}` : ''}</div>
              </div>
            </div>
            <div className="vs-save"><Ico d="spark" size={14}/>Save {money(save)} on the full package — same approved look, delivered in 24–48 hours instead of weeks.</div>
          </div>

          <div className="pp-foot">
            <button className="btn btn-accent" onClick={() => onStart(L.id)}>
              <Ico d="spark" size={15}/>Start this package
            </button>
            <span className="pp-rate"><strong>{money(aiSet)}</strong> for the {q.paid} new image{q.paid === 1 ? '' : 's'}{q.free ? ` · ${q.free} shared free` : ''} · or {money(aiTotal)} full package with A+ &amp; video · billed on approval</span>
          </div>
        </>
      )}
    </div>
  );
}

Object.assign(window, { ExpandedContent, PendingPanel, DCard, VideoCard, SectionHead });
