// Prodz — own-profile library: the "MIE cose" pages reached from the profile
// section rows (Productions · Shoutouts · Locations · Gear · Threads), the
// Archived mirror of those sections, and Settings (language).
//
//   · SettingsScreen   — app settings; currently the language toggle.
//   · ArchivedLibrary  — same five sections, but the archived posts.
//   · MySection        — one section's items (active or archived).
//   · ProfileSectionRows — the tappable row list, shared by profile + archive.

// ---- The five "my things" sections ----
const PROFILE_SECTIONS = [
  { id: 'prods',     icon: 'Clapperboard',   label: { it: 'Produzioni', en: 'Productions' } },
  { id: 'shouts',    icon: 'Megaphone',      label: { it: 'Shoutouts', en: 'Shoutouts' } },
  { id: 'locations', icon: 'MapPin',         label: { it: 'Location', en: 'Locations' } },
  { id: 'gear',      icon: 'Camera',         label: { it: 'Gear', en: 'Gear' } },
  { id: 'threads',   icon: 'MessagesSquare', label: { it: 'Threads', en: 'Threads' } },
];

// ---- "Mine" datasets, split active vs archived (mock) ----
const MY_PRODS_ARCHIVED = [
  { id: 'arch-aurora', title: 'Aurora — Test', image: IMG.studio,   cat: 'TEST',      meta: { it: 'Test luce · 2024', en: 'Lighting test · 2024' } },
  { id: 'arch-metro',  title: 'Linee Metro',   image: IMG.interior, cat: 'REPORTAGE', meta: { it: 'Reportage · 2023', en: 'Reportage · 2023' } },
];
const MY_GEAR_ITEMS = [
  { id: 'mg1', name: 'Sony FX6',         kind: { it: 'Cinema camera', en: 'Cinema camera' }, img: IMG.camera, icon: 'Camera' },
  { id: 'mg2', name: 'Sigma 85mm f/1.4', kind: { it: 'Obiettivo', en: 'Lens' },              img: IMG.lens,   icon: 'Aperture' },
  { id: 'mg3', name: 'Aputure 600d Pro', kind: { it: 'Illuminazione', en: 'Lighting' },      img: null,       icon: 'Lightbulb' },
];
const MY_GEAR_ARCHIVED = [
  { id: 'mg4', name: 'Canon C300 Mk II', kind: { it: 'Cinema camera', en: 'Cinema camera' }, img: null, icon: 'Camera' },
];
const MY_LOC_ACTIVE = ['loft', 'rooftop'].map((id) => LOCATIONS_ALL.find((l) => l.id === id)).filter(Boolean);
const MY_LOC_ARCHIVED = ['garage'].map((id) => LOCATIONS_ALL.find((l) => l.id === id)).filter(Boolean);
const MY_THREADS_ACTIVE = THREADS.slice(0, 2);
const MY_THREADS_ARCHIVED = THREADS.slice(2);

// Normalised tiles for a given section + state. `tint` colours the badge.
function mySectionItems(section, archived, L, nav) {
  const T = (o) => o;
  switch (section) {
    case 'prods': {
      if (archived) return MY_PRODS_ARCHIVED.map((p) => T({ key: p.id, img: p.image, title: p.title, sub: tr(L, p.meta), badge: p.cat, tint: 'var(--prodz-teal)', onTap: () => nav.toast(L('Produzione archiviata', 'Archived production'), null) }));
      return PRODUCTIONS.map((p) => T({ key: p.id, img: p.image, title: p.title, sub: tr(L, p.meta), badge: p.cat, tint: 'var(--prodz-teal)', onTap: () => nav.openProduction(p.id) }));
    }
    case 'shouts': {
      const open = MY_SHOUTOUTS.filter((s) => s.status === 'open');
      const closed = MY_SHOUTOUTS.filter((s) => s.status !== 'open');
      return (archived ? closed : open).map((s) => {
        const prod = PRODUCTIONS.find((x) => x.id === s.prod);
        return T({ key: s.id, icon: s.kind === 'job' ? 'Megaphone' : 'Handshake', tint: s.kind === 'job' ? 'var(--prodz-gold)' : 'var(--prodz-teal)',
          title: tr(L, s.title), sub: `${prod ? prod.title : ''} · ${s.applicants} ${L('cand.', 'appl.')}`,
          badge: s.kind === 'job' ? L('Job Call', 'Job Call') : 'Collab',
          onTap: () => nav.openShoutout(s.id, 'me') });
      });
    }
    case 'locations': {
      return (archived ? MY_LOC_ARCHIVED : MY_LOC_ACTIVE).map((l) => T({ key: l.id, img: l.image, title: l.title, sub: tr(L, l.price), badge: 'Location', tint: 'var(--purple)', onTap: () => archived ? nav.toast(L('Annuncio archiviato', 'Archived listing'), null) : nav.openLocations() }));
    }
    case 'gear': {
      return (archived ? MY_GEAR_ARCHIVED : MY_GEAR_ITEMS).map((g) => T({ key: g.id, img: g.img, icon: g.icon, title: g.name, sub: tr(L, g.kind), badge: 'Gear', tint: 'var(--blue)', onTap: () => nav.toast(L('Apertura scheda gear…', 'Opening gear card…'), null) }));
    }
    case 'threads': {
      return (archived ? MY_THREADS_ARCHIVED : MY_THREADS_ACTIVE).map((th) => T({ key: th.id, icon: 'MessagesSquare', tint: 'var(--prodz-teal)', title: tr(L, th.title), sub: `${th.replies} ${L('risposte', 'replies')} · ${th.likes} ${L('mi piace', 'likes')}`, badge: 'Thread', onTap: () => nav.openThread(th.id) }));
    }
    default: return [];
  }
}

function mySectionCount(section, archived) {
  switch (section) {
    case 'prods':     return archived ? MY_PRODS_ARCHIVED.length : PRODUCTIONS.length;
    case 'shouts':    return MY_SHOUTOUTS.filter((s) => (archived ? s.status !== 'open' : s.status === 'open')).length;
    case 'locations': return (archived ? MY_LOC_ARCHIVED : MY_LOC_ACTIVE).length;
    case 'gear':      return (archived ? MY_GEAR_ARCHIVED : MY_GEAR_ITEMS).length;
    case 'threads':   return (archived ? MY_THREADS_ARCHIVED : MY_THREADS_ACTIVE).length;
    default:          return 0;
  }
}

// ---- Horizontal section navbar + inline grid (profile + archive share it) ----
function ProfileSections({ archived = false }) {
  const { L } = useL();
  const nav = useNav();
  const [tab, setTab] = useStateS('prods');
  const def = PROFILE_SECTIONS.find((s) => s.id === tab) || PROFILE_SECTIONS[0];
  const items = mySectionItems(tab, archived, L, nav);
  return (
    <div>
      {/* underline tab bar — teal active indicator (scrolls if needed) */}
      <div className="hscroll" style={{ padding: '0 16px', gap: 24, borderBottom: '1px solid var(--border-hairline)' }}>
        {PROFILE_SECTIONS.map((s) => {
          const active = s.id === tab;
          return (
            <button key={s.id} onClick={() => setTab(s.id)} style={{ position: 'relative', flexShrink: 0, background: 'none', border: 'none', cursor: 'pointer', padding: '2px 0 13px', fontFamily: 'var(--font-ui)', fontSize: 14, fontWeight: 700, color: active ? 'var(--text-primary)' : 'var(--text-subtle)', transition: 'color var(--dur-base) var(--ease-standard)' }}>
              {tr(L, s.label)}
              {active && <span style={{ position: 'absolute', left: 0, right: 0, bottom: -1, height: 2, borderRadius: 2, background: 'var(--prodz-teal)' }} />}
            </button>
          );
        })}
      </div>

      {/* count line */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '14px 16px 0' }}>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 7, fontSize: 12.5, color: 'var(--text-muted)' }}>
          <Ic n={def.icon} s={14} color="var(--prodz-teal)" />
          <b style={{ color: 'var(--text-primary)', fontVariantNumeric: 'tabular-nums' }}>{items.length}</b> {tr(L, def.label).toLowerCase()}
        </span>
      </div>

      <div style={{ padding: '12px 16px 0' }}>
        <LibraryGrid items={items} archived={archived} />
      </div>
    </div>
  );
}

// ---- Grid of a section's items ----
function LibraryGrid({ items, archived }) {
  const { L } = useL();
  if (!items.length) {
    return <p style={{ textAlign: 'center', fontSize: 13, color: 'var(--text-subtle)', padding: '34px 0' }}>{archived ? L('Niente di archiviato qui.', 'Nothing archived here.') : L('Ancora nessun elemento.', 'No items yet.')}</p>;
  }
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
      {items.map((it) => (
        <button key={it.key} onClick={it.onTap} style={{
          position: 'relative', height: 150, padding: 0, border: 'none', cursor: 'pointer', textAlign: 'left', overflow: 'hidden',
          borderRadius: 'var(--radius-md)', boxShadow: 'var(--ring-inset-hairline)',
          background: it.img ? `var(--surface-raised) url(${it.img}) center/cover` : 'var(--surface-card)',
        }}>
          {!it.img && (
            <span style={{ position: 'absolute', top: 14, left: 14, width: 44, height: 44, borderRadius: 12, background: 'var(--surface-raised)', boxShadow: 'var(--ring-inset-hairline)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <Ic n={it.icon || 'Image'} s={22} color="var(--text-muted)" />
            </span>
          )}
          <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(180deg, rgba(15,15,17,0) 38%, rgba(15,15,17,0.9))' }} />
          <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: it.tint, fontSize: 9, fontWeight: 800, letterSpacing: '0.06em', textTransform: 'uppercase' }}>{it.badge}</span>
          {archived && (
            <span style={{ position: 'absolute', top: 10, right: 10, width: 24, height: 24, borderRadius: '50%', background: 'rgba(0,0,0,0.55)', backdropFilter: 'blur(6px)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <Ic n="Archive" s={12} color="var(--gray-200)" />
            </span>
          )}
          <div style={{ position: 'absolute', left: 11, right: 11, bottom: 10 }}>
            <div style={{ fontSize: 13, fontWeight: 700, color: '#fff', lineHeight: 1.25, textWrap: 'pretty' }}>{it.title}</div>
            <div style={{ fontSize: 10.5, color: 'var(--gray-200)', marginTop: 2 }}>{it.sub}</div>
          </div>
        </button>
      ))}
    </div>
  );
}

// ---- One section's page (active or archived) ----
function MySection({ section, archived }) {
  const { L } = useL();
  const nav = useNav();
  const def = PROFILE_SECTIONS.find((s) => s.id === section) || PROFILE_SECTIONS[0];
  const items = mySectionItems(section, archived, L, nav);
  return (
    <div className="pz-screen-enter" style={{ paddingBottom: 28 }}>
      <TopBar title={archived ? L('Archivio', 'Archive') : tr(L, def.label)} onBack={nav.pop} showLang={false} />
      <div style={{ padding: '16px 16px 4px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
          <Ic n={def.icon} s={20} color="var(--prodz-teal)" />
          <h1 style={pageTitle}>{tr(L, def.label)}</h1>
        </div>
        <p style={pageSub}>{archived
          ? L('I tuoi post archiviati in questa sezione.', 'Your archived posts in this section.')
          : L('Tutto ciò che hai pubblicato qui.', 'Everything you posted here.')}</p>
      </div>
      <div style={{ padding: '14px 16px 0' }}>
        <LibraryGrid items={items} archived={archived} />
      </div>
    </div>
  );
}

// ---- Archived library: the five sections, archived state ----
function ArchivedLibrary() {
  const { L } = useL();
  const nav = useNav();
  return (
    <div className="pz-screen-enter" style={{ paddingBottom: 28 }}>
      <TopBar title={L('Archivio', 'Archive')} onBack={nav.pop} showLang={false} />
      <div style={{ padding: '16px 16px 4px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
          <Ic n="Archive" s={20} color="var(--prodz-teal)" />
          <h1 style={pageTitle}>{L('Archivio', 'Archive')}</h1>
        </div>
        <p style={pageSub}>{L('I tuoi post archiviati, per sezione.', 'Your archived posts, by section.')}</p>
      </div>
      <div style={{ padding: '16px 0 0' }}>
        <ProfileSections archived={true} />
      </div>
    </div>
  );
}

// ---- Settings: language toggle (moved out of the navbar) ----
function SettingsScreen() {
  const { L } = useL();
  const nav = useNav();
  return (
    <div className="pz-screen-enter" style={{ paddingBottom: 28 }}>
      <TopBar title={L('Impostazioni', 'Settings')} onBack={nav.pop} showLang={false} />
      <div style={{ padding: '16px 16px 4px' }}>
        <h1 style={pageTitle}>{L('Impostazioni', 'Settings')}</h1>
        <p style={pageSub}>{L('Preferenze dell’app.', 'App preferences.')}</p>
      </div>
      <div style={{ padding: '20px 16px 0' }}>
        <Eyebrow style={{ marginBottom: 10 }}>{L('Lingua', 'Language')}</Eyebrow>
        <div style={{ display: 'flex', alignItems: 'center', gap: 13, padding: '14px 14px', borderRadius: 'var(--radius-md)', background: 'var(--surface-card)', boxShadow: 'var(--ring-inset-hairline)' }}>
          <span style={{ width: 38, height: 38, borderRadius: 11, flexShrink: 0, background: 'var(--surface-raised)', boxShadow: 'var(--ring-inset-hairline)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Ic n="Globe" s={19} color="var(--prodz-teal)" />
          </span>
          <span style={{ flex: 1, minWidth: 0 }}>
            <span style={{ display: 'block', fontSize: 14.5, fontWeight: 700, color: 'var(--text-primary)' }}>{L('Lingua dell’app', 'App language')}</span>
            <span style={{ display: 'block', fontSize: 12, color: 'var(--text-muted)', marginTop: 1 }}>{L('Italiano · English', 'Italian · English')}</span>
          </span>
          <LangToggle compact={false} />
        </div>
      </div>
    </div>
  );
}

Object.assign(window, {
  PROFILE_SECTIONS, mySectionItems, mySectionCount,
  ProfileSections, LibraryGrid, MySection, ArchivedLibrary, SettingsScreen,
});
