/* global React */
const { useState: useTalentState, useMemo: useTalentMemo, useEffect: useTalentEffect } = React;

// ─────────────────────────────────────────────────────────────
// OUR TALENT — public roster of CentreStage Agency talent.
// Data lives in talent-data.js (window.CS_TALENT). Public fields
// only: display name, headshot, height, credits, training, skills
// and showreel. No contact details, dates of birth, schools or
// locations are ever included. Youth show first name + initial.
// ─────────────────────────────────────────────────────────────

const TALENT_CATS = ['Theatre', 'Musical Theatre', 'Screen', 'Commercial', 'Dance', 'Voice'];

const talentHeightBand = (h) => {
  const n = parseInt(h, 10);
  if (!n) return '';
  if (n < 140) return 'Under 140 cm';
  if (n < 155) return '140–154 cm';
  if (n < 165) return '155–164 cm';
  if (n < 175) return '165–174 cm';
  if (n < 185) return '175–184 cm';
  return '185 cm +';
};
const HEIGHT_BANDS = ['Under 140 cm', '140–154 cm', '155–164 cm', '165–174 cm', '175–184 cm', '185 cm +'];

const TalentChip = ({ active, onClick, children }) => (
  <button type="button" onClick={onClick}
    style={{
      fontFamily: 'var(--font-sans)', fontSize: 12, fontWeight: 700, letterSpacing: '0.06em',
      textTransform: 'uppercase', padding: '10px 14px', cursor: 'pointer',
      border: '1px solid var(--ink)', background: active ? 'var(--ink)' : 'transparent',
      color: active ? 'var(--paper)' : 'var(--ink)',
    }}>
    {children}
  </button>
);

const TalentSelect = ({ label, value, onChange, options }) => (
  <label style={{ display: 'flex', flexDirection: 'column', gap: 6, minWidth: 170, flex: '1 1 170px' }}>
    <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--mid)', letterSpacing: '0.08em', textTransform: 'uppercase' }}>{label}</span>
    <select value={value} onChange={(e) => onChange(e.target.value)}
      style={{ height: 46, border: '1px solid var(--ink)', background: 'var(--paper)', color: 'var(--ink)', fontFamily: 'var(--font-sans)', fontSize: 15, padding: '0 12px', borderRadius: 0 }}>
      <option value="">All</option>
      {options.map(o => <option key={o} value={o}>{o}</option>)}
    </select>
  </label>
);

const TalentHeadshot = ({ t, style }) => (
  t.img
    ? <img src={t.img} alt={`${t.name} headshot`} loading="lazy"
        style={{ width: '100%', aspectRatio: '4 / 5', objectFit: 'cover', objectPosition: 'center 25%', display: 'block', background: '#e9e6df', ...style }} />
    : <div style={{ width: '100%', aspectRatio: '4 / 5', background: '#e9e6df', display: 'flex', alignItems: 'center', justifyContent: 'center', ...style }}>
        <span style={{ fontFamily: 'var(--font-display)', fontWeight: 900, fontSize: 56, color: '#b9b4a8' }}>/</span>
      </div>
);

const TalentCard = ({ t, onOpen }) => (
  <button type="button" onClick={() => onOpen(t)} aria-label={`View ${t.name}`}
    style={{ textAlign: 'left', background: 'transparent', border: 0, padding: 0, cursor: 'pointer', color: 'var(--ink)' }}>
    <div style={{ border: '1px solid var(--ink)', overflow: 'hidden', position: 'relative' }}>
      <TalentHeadshot t={t} />
      {t.reel && (
        <span style={{ position: 'absolute', top: 10, left: 10, background: 'var(--ink)', color: 'var(--paper)', fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.08em', textTransform: 'uppercase', padding: '5px 8px' }}>
          ▶ Showreel
        </span>
      )}
    </div>
    <div style={{ padding: '12px 2px 0' }}>
      <div style={{ fontFamily: 'var(--font-display)', fontWeight: 900, fontSize: 20, letterSpacing: '-0.01em', lineHeight: 1.1 }}>{t.name}</div>
      <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--mid)', letterSpacing: '0.06em', textTransform: 'uppercase', marginTop: 6 }}>
        {t.type === 'youth' ? 'Youth' : 'Professional'}{t.height ? ` · ${t.height} cm` : ''}
      </div>
    </div>
  </button>
);

// CentreStage-format resume (matches the Resume Builder's branded template)
const TalentResume = ({ t }) => {
  const head = (s) => <div style={{ fontSize: 12, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', margin: '0 0 8px' }}>{s}</div>;
  const groups = {};
  (t.credits || []).forEach(c => { const k = c.section || 'Credits'; (groups[k] = groups[k] || []).push(c); });
  return (
    <div style={{ background: '#fff', color: '#0a0a0a', padding: 'clamp(20px, 4vw, 48px)', fontFamily: 'Georgia, serif', border: '1px solid #0a0a0a' }}>
      <div style={{ display: 'flex', gap: 24, borderBottom: '2px solid #0a0a0a', paddingBottom: 22, marginBottom: 22, flexWrap: 'wrap' }}>
        <div style={{ width: 150, flexShrink: 0, border: '1px solid #0a0a0a' }}><TalentHeadshot t={t} /></div>
        <div style={{ flex: '1 1 240px' }}>
          <img src={(window.__resources && window.__resources.logoBlack) || 'assets/logo/CentreStage-Solid-Black.png'} alt="CentreStage Agency" style={{ height: 30, marginBottom: 12, display: 'block' }} />
          <div style={{ fontSize: 30, fontWeight: 700, letterSpacing: '-0.01em' }}>{t.name}</div>
          {t.height && <div style={{ fontSize: 14, color: '#444', marginTop: 8 }}>Height: {t.height} cm</div>}
          <div style={{ marginTop: 14, fontSize: 13, fontWeight: 700, letterSpacing: '0.03em' }}>
            Represented by CentreStage Agency<br/>
            <span style={{ fontWeight: 400, color: '#444' }}>Enquiries via the agency only · www.centrestageagency.org.au</span>
          </div>
        </div>
      </div>

      {Object.keys(groups).length ? Object.keys(groups).map(sec => (
        <div key={sec} style={{ marginBottom: 22 }}>
          {head(sec)}
          <div style={{ overflowX: 'auto' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13, minWidth: 420 }}>
              <thead>
                <tr style={{ borderBottom: '1px solid #0a0a0a' }}>
                  {['Production', 'Role', 'Company / Director', 'Year'].map(h => <th key={h} style={{ textAlign: 'left', padding: '6px 10px 6px 0', fontWeight: 700 }}>{h}</th>)}
                </tr>
              </thead>
              <tbody>
                {groups[sec].map((c, i) => (
                  <tr key={i} style={{ borderBottom: '1px solid #ddd' }}>
                    <td style={{ padding: '6px 10px 6px 0' }}>{c.production}</td>
                    <td style={{ padding: '6px 10px 6px 0' }}>{c.role}</td>
                    <td style={{ padding: '6px 10px 6px 0' }}>{c.company}</td>
                    <td style={{ padding: '6px 10px 6px 0', whiteSpace: 'nowrap' }}>{c.year}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )) : (
        <div style={{ marginBottom: 22 }}>{head('Credits')}<div style={{ fontSize: 13, color: '#666' }}>Credits available on request from the agency.</div></div>
      )}

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(240px, 1fr))', gap: 24 }}>
        {t.training && t.training.length > 0 && (
          <div>
            {head('Training')}
            {t.training.map((x, i) => <div key={i} style={{ padding: '6px 0', borderBottom: '1px solid #ddd', fontSize: 13 }}>{x}</div>)}
          </div>
        )}
        {t.skills && t.skills.length > 0 && (
          <div>
            {head('Skills')}
            <p style={{ fontSize: 13, lineHeight: 1.6, margin: 0 }}>{t.skills.join(' · ')}</p>
          </div>
        )}
      </div>
      <div style={{ marginTop: 26, paddingTop: 10, borderTop: '1px solid #ccc', fontSize: 11, color: '#666', textAlign: 'center' }}>
        CentreStage Agency · www.centrestageagency.org.au
      </div>
    </div>
  );
};

const TalentProfile = ({ t, onClose, navigate }) => {
  useTalentEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => { window.removeEventListener('keydown', onKey); document.body.style.overflow = ''; };
  }, []);
  const embed = (u) => {
    if (!u) return null;
    let m = u.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/shorts\/)([\w-]{6,})/);
    if (m) return `https://www.youtube.com/embed/${m[1]}`;
    m = u.match(/vimeo\.com\/(\d+)/);
    if (m) return `https://player.vimeo.com/video/${m[1]}`;
    m = u.match(/drive\.google\.com\/file\/d\/([\w-]+)/);
    if (m) return `https://drive.google.com/file/d/${m[1]}/preview`;
    return null;
  };
  const src = embed(t.reel);
  return (
    <div role="dialog" aria-modal="true" aria-label={t.name} onClick={onClose}
      style={{ position: 'fixed', inset: 0, background: 'rgba(10,10,10,0.72)', zIndex: 200, overflowY: 'auto', padding: 'clamp(12px, 3vw, 40px)' }}>
      <div onClick={(e) => e.stopPropagation()} style={{ maxWidth: 1000, margin: '0 auto', background: 'var(--paper)', padding: 'clamp(18px, 3vw, 36px)', position: 'relative' }}>
        <button type="button" onClick={onClose} aria-label="Close"
          style={{ position: 'sticky', top: 0, float: 'right', zIndex: 2, width: 44, height: 44, border: '1px solid var(--ink)', background: 'var(--paper)', color: 'var(--ink)', fontSize: 20, cursor: 'pointer' }}>×</button>
        <Eyebrow style={{ color: 'var(--mid)' }}>{t.type === 'youth' ? 'Youth talent' : 'Professional talent'} <Slash /> CentreStage Agency</Eyebrow>
        <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 900, fontSize: 'clamp(36px, 6vw, 72px)', letterSpacing: '-0.03em', lineHeight: 0.95, margin: '18px 0 24px' }}>{t.name}</h2>
        {t.reel && (
          <div style={{ marginBottom: 28 }}>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--mid)', letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 10 }}>Showreel</div>
            {src
              ? <div style={{ position: 'relative', paddingTop: '56.25%', background: '#000', border: '1px solid var(--ink)' }}>
                  <iframe src={src} title={`${t.name} showreel`} allow="autoplay; encrypted-media; fullscreen; picture-in-picture" allowFullScreen loading="lazy"
                    style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', border: 0 }} />
                </div>
              : <a href={t.reel} target="_blank" rel="noopener" className="cs-btn">Watch showreel <span style={{ marginLeft: 8 }}>↗</span></a>}
          </div>
        )}
        <TalentResume t={t} />
        <div style={{ marginTop: 28, display: 'flex', gap: 12, flexWrap: 'wrap', alignItems: 'center' }}>
          <a href="#contact" onClick={(e) => { e.preventDefault(); onClose(); navigate('contact'); }} className="cs-btn">
            Enquire about {t.first || t.name.split(' ')[0]} <span style={{ marginLeft: 8 }}>→</span>
          </a>
          <span style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--mid)' }}>All bookings and enquiries go through CentreStage Agency.</span>
        </div>
      </div>
    </div>
  );
};

const TalentScreen = ({ navigate }) => {
  const all = (window.CS_TALENT || []).filter(t => t.published !== false);
  const [tab, setTab] = useTalentState('all');
  const [q, setQ] = useTalentState('');
  const [height, setHeight] = useTalentState('');
  const [cat, setCat] = useTalentState('');
  const [skill, setSkill] = useTalentState('');
  const [reelOnly, setReelOnly] = useTalentState(false);
  const [open, setOpen] = useTalentState(null);

  // Deep link: /talent#name-slug opens that profile
  useTalentEffect(() => {
    const h = window.location.hash.replace(/^#\/?/, '');
    if (h) { const t = all.find(x => x.id === h); if (t) setOpen(t); }
  }, []);

  const skillOpts = useTalentMemo(() => {
    const c = {};
    all.forEach(t => (t.skillTags || []).forEach(s => { c[s] = (c[s] || 0) + 1; }));
    return Object.keys(c).sort((a, b) => c[b] - c[a] || a.localeCompare(b)).slice(0, 40).sort();
  }, [all.length]);

  const list = useTalentMemo(() => {
    const qq = q.trim().toLowerCase();
    return all.filter(t =>
      (tab === 'all' || t.type === tab) &&
      (!height || talentHeightBand(t.height) === height) &&
      (!cat || (t.cats || []).includes(cat)) &&
      (!skill || (t.skillTags || []).includes(skill)) &&
      (!reelOnly || !!t.reel) &&
      (!qq || (t.search || t.name.toLowerCase()).includes(qq))
    ).sort((a, b) => a.name.localeCompare(b.name));
  }, [tab, q, height, cat, skill, reelOnly, all.length]);

  const reset = () => { setQ(''); setHeight(''); setCat(''); setSkill(''); setReelOnly(false); };

  return (
    <main data-screen-label="Our Talent">
      <section style={{ maxWidth: 1600, margin: '0 auto', padding: '56px 48px 0' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginBottom: 40 }}>
          <Eyebrow style={{ color: 'var(--mid)' }}>Our talent <Slash /> Roster</Eyebrow>
          <div style={{ flex: 1, height: 1, background: 'var(--hairline)' }} />
          <span className="cs-mono" style={{ color: 'var(--mid)' }}>Youth and professional</span>
        </div>
        <h1 style={{ fontFamily: 'var(--font-display)', fontWeight: 900, fontSize: 'clamp(52px, 8.5vw, 132px)', letterSpacing: '-0.035em', lineHeight: 0.9, margin: 0, color: 'var(--ink)' }}>
          Our talent.
        </h1>
        <p style={{ fontSize: 19, lineHeight: 1.55, color: 'var(--ink)', margin: '28px 0 0', maxWidth: '60ch' }}>
          Youth and professional performers represented by CentreStage Agency for theatre, musical theatre, screen and commercial work. Search the roster, open a profile for their resume and showreel, and contact the agency to request availability or submit for a role.
        </p>
      </section>

      <section style={{ maxWidth: 1600, margin: '0 auto', padding: '48px 48px 0' }}>
        <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', marginBottom: 24 }}>
          <TalentChip active={tab === 'all'} onClick={() => setTab('all')}>All</TalentChip>
          <TalentChip active={tab === 'youth'} onClick={() => setTab('youth')}>Youth</TalentChip>
          <TalentChip active={tab === 'pro'} onClick={() => setTab('pro')}>Professional</TalentChip>
        </div>
        <div style={{ display: 'flex', gap: 16, flexWrap: 'wrap', alignItems: 'flex-end', paddingBottom: 24, borderBottom: '1px solid var(--hairline)' }}>
          <label style={{ display: 'flex', flexDirection: 'column', gap: 6, flex: '2 1 260px' }}>
            <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--mid)', letterSpacing: '0.08em', textTransform: 'uppercase' }}>Search</span>
            <input type="search" value={q} onChange={(e) => setQ(e.target.value)} placeholder="Name, production, skill…"
              style={{ height: 46, border: '1px solid var(--ink)', background: 'var(--paper)', color: 'var(--ink)', fontFamily: 'var(--font-sans)', fontSize: 15, padding: '0 14px', borderRadius: 0 }} />
          </label>
          <TalentSelect label="Height" value={height} onChange={setHeight} options={HEIGHT_BANDS} />
          <TalentSelect label="Experience" value={cat} onChange={setCat} options={TALENT_CATS} />
          {skillOpts.length > 0 && <TalentSelect label="Skill" value={skill} onChange={setSkill} options={skillOpts} />}
          <label style={{ display: 'flex', alignItems: 'center', gap: 8, height: 46, fontFamily: 'var(--font-sans)', fontSize: 14, cursor: 'pointer' }}>
            <input type="checkbox" checked={reelOnly} onChange={(e) => setReelOnly(e.target.checked)} /> Has showreel
          </label>
          <button type="button" onClick={reset}
            style={{ height: 46, background: 'transparent', border: 0, textDecoration: 'underline', color: 'var(--mid)', cursor: 'pointer', fontFamily: 'var(--font-sans)', fontSize: 13 }}>Clear filters</button>
        </div>
      </section>

      <section style={{ maxWidth: 1600, margin: '0 auto', padding: '24px 48px 120px' }}>
        {list.length ? (
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(190px, 1fr))', gap: '36px 24px' }}>
            {list.map(t => <TalentCard key={t.id} t={t} onOpen={(x) => { setOpen(x); try { history.replaceState(null, '', '#' + x.id); } catch (e) {} }} />)}
          </div>
        ) : (
          <div style={{ padding: '80px 0', textAlign: 'center', color: 'var(--mid)' }}>No performers match those filters. <button type="button" onClick={reset} style={{ background: 'none', border: 0, textDecoration: 'underline', cursor: 'pointer', color: 'var(--ink)' }}>Clear filters</button></div>
        )}
      </section>

      <section style={{ background: 'var(--ink)', color: 'var(--paper)' }}>
        <div style={{ maxWidth: 1600, margin: '0 auto', padding: '96px 48px', display: 'flex', gap: 48, flexWrap: 'wrap', alignItems: 'flex-end', justifyContent: 'space-between' }}>
          <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 900, fontSize: 'clamp(40px, 6vw, 96px)', letterSpacing: '-0.035em', lineHeight: 0.92, margin: 0 }}>Casting a project?</h2>
          <a href="#contact" onClick={(e) => { e.preventDefault(); navigate('contact'); }} className="cs-btn"
            style={{ background: 'var(--paper)', color: 'var(--ink)', border: '1px solid var(--paper)' }}>Contact the agency <span style={{ marginLeft: 8 }}>→</span></a>
        </div>
      </section>

      {open && <TalentProfile t={open} navigate={navigate} onClose={() => { setOpen(null); try { history.replaceState(null, '', window.location.pathname); } catch (e) {} }} />}
    </main>
  );
};

Object.assign(window, { TalentScreen });
