// Prodz — Saved items & Locations marketplace.
//   · SavedItems          — review what you saved, organised in moodboards
//                           (folders of productions, locations, moments, gear).
//   · LocationsMarketplace — "Esplora" from Home opens a searchable, filterable
//                           catalogue of bookable spaces.

// ---------- resolve a saved reference to a display tile ----------
function resolveSaved(it, L) {
  if (it.t === 'production') { const p = PRODUCTIONS.find((x) => x.id === it.id); return p && { img: p.image, title: p.title, sub: tr(L, p.meta), badge: L('Produzione', 'Production'), tint: 'var(--prodz-teal)' }; }
  if (it.t === 'location')   { const p = LOCATIONS_ALL.find((x) => x.id === it.id); return p && { img: p.image, title: p.title, sub: tr(L, p.price), badge: 'Location', tint: 'var(--purple)' }; }
  if (it.t === 'moment')     { const p = MOMENTS.find((x) => x.id === it.id); return p && { img: p.image, title: tr(L, p.label), sub: 'Set Moment', badge: 'Moment', tint: 'var(--prodz-gold)' }; }
  if (it.t === 'gear')       { const p = GEAR.find((x) => x.id === it.id); return p && { img: p.img, icon: p.icon, title: p.name, sub: tr(L, p.price), badge: 'Gear', tint: 'var(--blue)' }; }
  return null;
}

function SavedItems() {
  const { L } = useL();
  const nav = useNav();
  const { Button } = window.ProdzDesignSystem_d0b87b;
  const boards = nav.moodboards;
  const [open, setOpen] = useStateS(null);
  const board = boards.find((b) => b.id === open);

  const openItem = (it) => {
    if (it.t === 'production') nav.openProduction(it.id);
    else if (it.t === 'location') nav.openLocations();
  };

  return (
    <div className="pz-screen-enter" style={{ paddingBottom: 28 }}>
      <TopBar title={board ? tr(L, board.name) : L('Elementi salvati', 'Saved items')} onBack={() => (board ? setOpen(null) : nav.pop())} showLang={false} />

      {!board && (
        <>
          <div style={{ padding: '16px 16px 4px' }}>
            <h1 style={pageTitle}>{L('Elementi salvati', 'Saved items')}</h1>
            <p style={pageSub}>{L('Rivedi ciò che hai salvato, raccolto in moodboard.', 'Review what you saved, gathered into moodboards.')}</p>
          </div>
          <div style={{ padding: '16px 16px 0', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            {boards.map((b) => (
              <button key={b.id} onClick={() => setOpen(b.id)} style={{ padding: 0, border: 'none', cursor: 'pointer', borderRadius: 'var(--radius-lg)', overflow: 'hidden', textAlign: 'left', background: 'var(--surface-card)', boxShadow: 'var(--ring-inset-hairline)' }}>
                <div style={{ position: 'relative', height: 120, background: `var(--surface-raised) url(${b.cover}) center/cover` }}>
                  <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(180deg, rgba(15,15,17,0) 40%, rgba(15,15,17,0.6))' }} />
                  <span style={{ position: 'absolute', top: 10, right: 10, minWidth: 22, height: 22, padding: '0 7px', borderRadius: 'var(--radius-pill)', background: 'rgba(0,0,0,0.55)', backdropFilter: 'blur(6px)', color: '#fff', fontSize: 11, fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{b.items.length}</span>
                </div>
                <div style={{ padding: '10px 12px 13px', display: 'flex', alignItems: 'center', gap: 7 }}>
                  <Ic n="Folder" s={15} color="var(--prodz-teal)" />
                  <span style={{ fontSize: 13.5, fontWeight: 700, color: 'var(--text-primary)' }}>{tr(L, b.name)}</span>
                </div>
              </button>
            ))}
            {/* create folder */}
            <button onClick={() => nav.toast(L('Nuova moodboard creata', 'New moodboard created'), null)} style={{ minHeight: 175, border: '1.5px dashed var(--border-strong)', cursor: 'pointer', borderRadius: 'var(--radius-lg)', background: 'transparent', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 8, color: 'var(--text-muted)' }}>
              <Ic n="Plus" s={24} color="var(--prodz-teal)" />
              <span style={{ fontSize: 12.5, fontWeight: 600 }}>{L('Nuova moodboard', 'New moodboard')}</span>
            </button>
          </div>
        </>
      )}

      {board && (
        <div style={{ padding: '16px 16px 0' }}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
            {board.items.map((it, i) => {
              const r = resolveSaved(it, L); if (!r) return null;
              return (
                <button key={i} onClick={() => openItem(it)} style={{ position: 'relative', height: 140, padding: 0, border: 'none', cursor: 'pointer', borderRadius: 'var(--radius-md)', overflow: 'hidden', textAlign: 'left', background: r.img ? `var(--surface-raised) url(${r.img}) center/cover` : 'var(--surface-raised)', boxShadow: 'var(--ring-inset-hairline)' }}>
                  {!r.img && <span style={{ position: 'absolute', top: 16, left: 16 }}><Ic n={r.icon || 'Image'} s={30} color="var(--text-muted)" /></span>}
                  <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(180deg, rgba(15,15,17,0) 42%, rgba(15,15,17,0.88))' }} />
                  <span style={{ position: 'absolute', top: 10, left: 10, padding: '3px 8px', borderRadius: 'var(--radius-pill)', background: 'rgba(0,0,0,0.55)', backdropFilter: 'blur(6px)', color: r.tint, fontSize: 9, fontWeight: 800, letterSpacing: '0.06em', textTransform: 'uppercase' }}>{r.badge}</span>
                  <div style={{ position: 'absolute', left: 11, right: 11, bottom: 10 }}>
                    <div style={{ fontSize: 13, fontWeight: 700, color: '#fff', lineHeight: 1.2 }}>{r.title}</div>
                    <div style={{ fontSize: 10.5, color: 'var(--gray-200)', marginTop: 2 }}>{r.sub}</div>
                  </div>
                </button>
              );
            })}
          </div>
        </div>
      )}
    </div>
  );
}

// ---------- Locations marketplace ----------
function LocationsMarketplace() {
  const { L } = useL();
  const nav = useNav();
  const { Button } = window.ProdzDesignSystem_d0b87b;
  const [q, setQ] = useStateS('');
  const [cat, setCat] = useStateS('ALL');
  const [sel, setSel] = useStateS(null);

  const list = LOCATIONS_ALL.filter((lc) => (cat === 'ALL' || lc.cat === cat) && (!q || lc.title.toLowerCase().includes(q.toLowerCase())));

  return (
    <div className="pz-screen-enter" style={{ paddingBottom: 28 }}>
      <TopBar title={L('Location', 'Locations')} onBack={nav.pop} showLang={false} />
      <div style={{ padding: '16px 16px 4px' }}>
        <h1 style={pageTitle}>{L('Marketplace location', 'Locations marketplace')}</h1>
        <p style={pageSub}>{L('Trova e prenota spazi per le tue produzioni.', 'Find and book spaces for your productions.')}</p>
      </div>

      {/* search */}
      <div style={{ padding: '14px 16px 0' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 9, height: 44, padding: '0 14px', borderRadius: 'var(--radius-pill)', background: 'var(--surface-raised)', boxShadow: 'var(--ring-inset-hairline)' }}>
          <Ic n="Search" s={17} color="var(--text-subtle)" />
          <input value={q} onChange={(e) => setQ(e.target.value)} placeholder={L('Cerca città, spazio…', 'Search city, space…')}
            style={{ flex: 1, background: 'none', border: 'none', outline: 'none', color: 'var(--text-body)', fontSize: 14 }} />
        </div>
      </div>

      {/* category filters */}
      <div className="hscroll" style={{ padding: '14px 16px 2px', gap: 8 }}>
        {['ALL'].concat(LOCATION_CATS).map((c) => (
          <FilterChip key={c} active={cat === c} onClick={() => setCat(c)} label={c === 'ALL' ? L('Tutte', 'All') : c} />
        ))}
      </div>

      {/* results */}
      <div style={{ padding: '12px 16px 0', display: 'flex', flexDirection: 'column', gap: 12 }}>
        {list.map((lc) => (
          <button key={lc.id} onClick={() => setSel(lc)} style={{ display: 'flex', gap: 12, width: '100%', padding: 10, border: 'none', cursor: 'pointer', textAlign: 'left', borderRadius: 'var(--radius-lg)', background: 'var(--surface-card)', boxShadow: 'var(--ring-inset-hairline)' }}>
            <span style={{ width: 96, height: 84, borderRadius: 'var(--radius-md)', flexShrink: 0, background: `url(${lc.image}) center/cover`, boxShadow: 'var(--ring-inset-hairline)' }} />
            <span style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
              <span style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
                <span style={{ fontSize: 15, fontWeight: 700, color: 'var(--text-primary)' }}>{lc.title}</span>
                {lc.sponsored && <Ic n="Sparkles" s={13} color="var(--prodz-gold)" />}
              </span>
              <span style={{ fontSize: 12, color: 'var(--text-muted)', marginTop: 3 }}>{tr(L, lc.meta)}</span>
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, marginTop: 8, fontSize: 12.5, fontWeight: 700, color: 'var(--prodz-teal)' }}>
                <Ic n="Tag" s={13} color="var(--prodz-teal)" />{tr(L, lc.price)}
              </span>
            </span>
          </button>
        ))}
        {list.length === 0 && <p style={{ textAlign: 'center', fontSize: 13, color: 'var(--text-subtle)', padding: '24px 0' }}>{L('Nessuna location trovata.', 'No locations found.')}</p>}
      </div>

      <Sheet open={!!sel} onClose={() => setSel(null)}>
        {sel && (
          <div>
            <div style={{ display: 'flex', gap: 12 }}>
              <span style={{ width: 70, height: 70, borderRadius: 14, background: `url(${sel.image}) center/cover`, flexShrink: 0, boxShadow: 'var(--ring-inset-hairline)' }} />
              <div style={{ flex: 1 }}>
                {sel.sponsored && <Eyebrow color="var(--prodz-gold)" style={{ marginBottom: 4 }}>{L('In evidenza · Sponsorizzato', 'Featured · Sponsored')}</Eyebrow>}
                <div style={{ fontSize: 17, fontWeight: 700, color: 'var(--text-primary)' }}>{sel.title}</div>
                <div style={{ fontSize: 12.5, color: 'var(--text-muted)', marginTop: 2 }}>{tr(L, sel.meta)} · {tr(L, sel.price)}</div>
              </div>
            </div>
            <div style={{ display: 'flex', gap: 10, marginTop: 16 }}>
              <Button variant="secondary" fullWidth leadingIcon={<Ic n="Bookmark" s={16} />} onClick={() => { setSel(null); nav.toast(L('Salvato negli elementi', 'Saved to your items'), null); }}>{L('Salva', 'Save')}</Button>
              <Button variant="primary" glow fullWidth leadingIcon={<Ic n="Send" s={16} />} onClick={() => { setSel(null); nav.openInbox(); }}>{L('Contatta', 'Contact')}</Button>
            </div>
          </div>
        )}
      </Sheet>
    </div>
  );
}

function FilterChip({ active, onClick, label }) {
  return (
    <button onClick={onClick} style={{
      flexShrink: 0, border: 'none', cursor: 'pointer', height: 34, padding: '0 14px', borderRadius: 'var(--radius-pill)',
      fontSize: 12, fontWeight: 700, letterSpacing: '0.03em', whiteSpace: 'nowrap',
      background: active ? 'var(--teal-surface)' : 'var(--surface-raised)',
      color: active ? 'var(--prodz-teal)' : 'var(--text-muted)',
      boxShadow: active ? 'var(--ring-teal)' : 'var(--ring-inset-hairline)',
    }}>{label}</button>
  );
}

Object.assign(window, { SavedItems, LocationsMarketplace, FilterChip });
