/* Projects (reference projects) + Clients screens. */
const NSP = window.__FT_NS;
const { Card: CardP, Badge: BadgeP, Button: BtnP, Icon: IconP, ClientLogo: ClientP, IconTile: TileP } = NSP;
const DP = window.FT_DATA;
const projImg = (p) => p.img ? './assets/' + p.img : './assets/photography/' + p.photo;

function ProjectCard({ p, i, onOpen }) {
  const [hover, setHover] = React.useState(false);
  const real = !!p.img;
  return (
    <Reveal delay={(i % 3) * 80}>
      <CardP padding={0} interactive hovered={hover} onHoverChange={setHover}
        style={{ overflow: 'hidden', height: '100%', cursor: 'pointer' }} onClick={() => onOpen(p)}>
        <div style={{ position: 'relative', height: 190, overflow: 'hidden' }}>
          <img src={projImg(p)} alt="" style={{
            width: '100%', height: '100%', objectFit: 'cover', display: 'block',
            filter: real ? (hover ? 'grayscale(0)' : 'grayscale(.6)') : 'grayscale(1)',
            transform: hover ? 'scale(1.05)' : 'none', transition: 'transform 600ms var(--ease), filter 400ms var(--ease)'
          }} />
          <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(180deg, rgb(0 0 0 / .15) 0%, rgb(0 0 0 / .78) 100%)' }} />
          {p.gallery && p.gallery.length ? (
            <div style={{ position: 'absolute', top: 14, right: 14, display: 'flex', gap: 6, alignItems: 'center', height: 26, padding: '0 10px', borderRadius: 999, background: 'rgb(0 0 0 / .55)', backdropFilter: 'blur(6px)', color: '#fff', fontSize: 12, fontWeight: 600 }}>
              <IconP name="image" size={13} />{p.gallery.length + 1}
            </div>
          ) : null}
          <div style={{ position: 'absolute', left: 20, right: 20, bottom: 16, display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 12 }}>
            <div>
              <div style={{ fontFamily: 'var(--font-label)', fontWeight: 700, fontSize: 11, letterSpacing: 'var(--tracking-widest)', textTransform: 'uppercase', color: 'var(--brand-yellow)' }}>{p.sector}</div>
              <div style={{ fontFamily: 'var(--font-heading)', fontWeight: 700, fontSize: 19, marginTop: 5, color: '#fff' }}>{p.title}</div>
            </div>
            <BadgeP tone="brand" size="sm">{p.scope}</BadgeP>
          </div>
        </div>
        <div style={{ padding: 24, display: 'flex', flexDirection: 'column', gap: 14 }}>
          {p.summary ? <p style={{ fontSize: 14, lineHeight: 1.6, color: 'var(--text-secondary)', margin: 0, display: '-webkit-box', WebkitLineClamp: 3, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>{p.summary}</p> : null}
          <div style={{ display: 'flex', gap: 8, alignItems: 'center', fontSize: 14, color: 'var(--text-secondary)' }}>
            <span style={{ color: 'var(--brand-yellow)' }}><IconP name="map-pin" size={16} /></span>{p.location}
          </div>
          <div style={{ display: 'flex', gap: 8, alignItems: 'center', fontSize: 14, color: 'var(--text-secondary)' }}>
            <span style={{ color: 'var(--brand-yellow)' }}><IconP name="briefcase" size={16} /></span>{p.role}
          </div>
          <div style={{ display: 'flex', gap: 8, alignItems: 'center', fontSize: 14, color: 'var(--text-secondary)', paddingTop: 14, borderTop: '1px solid var(--border-subtle)' }}>
            <span style={{ color: 'var(--brand-yellow)' }}><IconP name="building-2" size={16} /></span>{p.client}
          </div>
        </div>
      </CardP>
    </Reveal>
  );
}

function DrawerLabel({ children }) {
  return <div style={{ fontFamily: 'var(--font-label)', fontWeight: 700, fontSize: 11, letterSpacing: 'var(--tracking-widest)', textTransform: 'uppercase', color: 'var(--text-muted)', marginBottom: 12 }}>{children}</div>;
}

function ProjectDrawer({ p, onClose }) {
  const panel = React.useRef(null);
  React.useEffect(() => { if (p && panel.current) panel.current.scrollTop = 0; }, [p && p.id]);
  if (!p) return null;
  return ReactDOM.createPortal((
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, zIndex: 1050, background: 'rgb(0 0 0 / .6)',
      display: 'flex', justifyContent: 'flex-end', animation: 'ftFade 200ms var(--ease)'
    }}>
      <div ref={panel} onClick={(e) => e.stopPropagation()} style={{
        width: 'min(640px, 100%)', height: '100%', overflowY: 'auto', background: 'var(--surface-card)',
        borderLeft: '1px solid var(--border-default)', padding: 32, boxSizing: 'border-box',
        animation: 'ftSlide 300ms var(--ease)'
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 16 }}>
          <div>
            <div style={{ fontFamily: 'var(--font-label)', fontWeight: 700, fontSize: 11, letterSpacing: 'var(--tracking-widest)', textTransform: 'uppercase', color: 'var(--brand-yellow)' }}>{p.sector}</div>
            <h3 style={{ fontSize: 26, fontWeight: 700, margin: '8px 0 0', letterSpacing: 'var(--tracking-tight)' }}>{p.title}</h3>
          </div>
          <BtnP variant="ghost" size="icon" icon="x" aria-label="Close" onClick={onClose} />
        </div>
        <img src={projImg(p)} alt="" style={{ width: '100%', height: 260, objectFit: 'cover', filter: p.img ? 'none' : 'grayscale(1)', borderRadius: 'var(--radius-lg)', margin: '24px 0 0', display: 'block' }} />
        {p.summary ? <p style={{ fontSize: 16, lineHeight: 1.65, color: 'var(--text-primary)', margin: '24px 0 0' }}>{p.summary}</p> : null}
        {p.narrative ? <p style={{ fontSize: 15, lineHeight: 1.7, color: 'var(--text-secondary)', margin: '14px 0 0' }}>{p.narrative}</p> : null}
        <dl style={{ margin: '24px 0 0', display: 'grid', gridTemplateColumns: '116px 1fr', rowGap: 14, columnGap: 16, fontSize: 15 }}>
          {[['Client', p.client],
            ['Location', p.location],
            ['Scope', p.scope],
            ['Our role', p.role]].map(([k, v]) => (
              <React.Fragment key={k}>
                <dt style={{ color: 'var(--text-muted)' }}>{k}</dt>
                <dd style={{ margin: 0, color: 'var(--text-primary)' }}>{v}</dd>
              </React.Fragment>
            ))}
        </dl>
        {p.programme ? (
          <div style={{ marginTop: 28 }}>
            <DrawerLabel>Programme</DrawerLabel>
            <ul style={{ margin: 0, padding: 0, listStyle: 'none', display: 'flex', flexDirection: 'column', gap: 8 }}>
              {p.programme.map((s) => (
                <li key={s} style={{ display: 'flex', gap: 10, fontSize: 14, lineHeight: 1.5, color: 'var(--text-secondary)' }}>
                  <span style={{ flex: '0 0 6px', width: 6, height: 6, borderRadius: 1, background: 'var(--brand-yellow)', marginTop: 7 }} />{s}
                </li>
              ))}
            </ul>
          </div>
        ) : null}
        {p.packages ? (
          <div style={{ marginTop: 28 }}>
            <DrawerLabel>Design packages produced</DrawerLabel>
            <ul style={{ margin: 0, padding: 0, listStyle: 'none', display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(220px,1fr))', gap: 8 }}>
              {p.packages.map((s) => (
                <li key={s} style={{ display: 'flex', gap: 10, fontSize: 14, lineHeight: 1.5, color: 'var(--text-secondary)' }}>
                  <span style={{ color: 'var(--brand-yellow)', flexShrink: 0, marginTop: 2 }}><IconP name="check" size={15} /></span>{s}
                </li>
              ))}
            </ul>
          </div>
        ) : null}
        <div style={{ marginTop: 28 }}>
          <DrawerLabel>Services delivered</DrawerLabel>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
            {p.services.map((s) => <BadgeP key={s} tone="brandOutline" size="sm">{s}</BadgeP>)}
          </div>
        </div>
        {p.gallery && p.gallery.length ? (
          <div style={{ marginTop: 28 }}>
            <DrawerLabel>{p.gallery.length + 1} project views</DrawerLabel>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(160px,1fr))', gap: 10 }}>
              {p.gallery.map((g) => (
                <figure key={g.f} style={{ margin: 0 }}>
                  <img src={'./assets/' + g.f} alt={g.c} style={{ width: '100%', aspectRatio: '4/3', objectFit: 'cover', borderRadius: 'var(--radius-md)', display: 'block' }} />
                  <figcaption style={{ fontSize: 12, color: 'var(--text-muted)', marginTop: 6 }}>{g.c}</figcaption>
                </figure>
              ))}
            </div>
          </div>
        ) : null}
      </div>
    </div>
  ), document.body);
}

function ProjectsScreen({ go }) {
  const [sector, setSector] = React.useState('All');
  const [open, setOpen] = React.useState(null);
  const spotlight = DP.projects.find((x) => x.id === 'p9');
  const sectors = ['All'].concat([...new Set(DP.projects.map((p) => p.sector))]);
  const shown = sector === 'All' ? DP.projects : DP.projects.filter((p) => p.sector === sector);
  return (
    <div>
      <PageHero eyebrow="Reference Projects" photo="skyline-dubai-bw.png"
        title="A portfolio of successful projects across the region"
        lede="Selected engagements across healthcare, luxury residential, hospitality, entertainment, oil and gas and commercial fit-out — in the UAE, KSA and Egypt." />

      <Section tone="page" pad={96}>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 36 }}>
          {sectors.map((s) => (
            <button key={s} onClick={() => setSector(s)} style={{
              height: 34, padding: '0 14px', borderRadius: 'var(--radius-full)', cursor: 'pointer',
              fontFamily: 'var(--font-body)', fontSize: 14, fontWeight: 600,
              background: sector === s ? 'var(--brand-yellow)' : 'transparent',
              color: sector === s ? 'var(--text-on-brand)' : 'var(--text-secondary)',
              border: '1px solid ' + (sector === s ? 'var(--brand-yellow)' : 'var(--border-default)'),
              transition: 'all var(--dur-base) var(--ease)'
            }}>{s}</button>
          ))}
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(320px,1fr))', gap: 32 }}>
          {shown.map((p, i) => <ProjectCard key={p.id} p={p} i={i} onOpen={setOpen} />)}
        </div>
      </Section>

      <Section tone="ink">
        <SectionHead eyebrow="Project spotlight" title={spotlight.title}
          lede={spotlight.location + ' · ' + spotlight.role} />
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(200px,1fr))', gap: 12, marginBottom: 32 }}>
          {[{ f: spotlight.img, c: 'Main elevation' }].concat(spotlight.gallery.slice(0, 3)).map((g) => (
            <Reveal key={g.f}>
              <figure style={{ margin: 0 }}>
                <img src={'./assets/' + g.f} alt={g.c} style={{ width: '100%', aspectRatio: '4/3', objectFit: 'cover', borderRadius: 'var(--radius-lg)', display: 'block' }} />
                <figcaption style={{ fontSize: 12, color: 'var(--text-muted)', marginTop: 8 }}>{g.c}</figcaption>
              </figure>
            </Reveal>
          ))}
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(280px,1fr))', gap: 40 }}>
          <Reveal>
            <p style={{ fontSize: 17, lineHeight: 1.7, color: 'var(--text-secondary)', margin: 0 }}>{spotlight.narrative}</p>
            <div style={{ marginTop: 24 }}><BtnP variant="primary" iconAfter="arrow-right" onClick={() => setOpen(spotlight)}>Full project detail</BtnP></div>
          </Reveal>
          <Reveal delay={120}>
            <DrawerLabel>Programme</DrawerLabel>
            <ul style={{ margin: 0, padding: 0, listStyle: 'none', display: 'grid', gap: 10 }}>
              {spotlight.programme.map((s) => (
                <li key={s} style={{ display: 'flex', gap: 10, fontSize: 15, lineHeight: 1.5, color: 'var(--text-secondary)' }}>
                  <span style={{ flex: '0 0 6px', width: 6, height: 6, borderRadius: 1, background: 'var(--brand-yellow)', marginTop: 8 }} />{s}
                </li>
              ))}
            </ul>
          </Reveal>
        </div>
      </Section>

      <Section tone="card">
        <SectionHead align="center" eyebrow="How we report" title="Every project reports the same six things"
          lede="Consistent reporting is the deliverable clients notice first: one format, one cadence, no surprises." />
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(220px,1fr))', gap: 32 }}>
          {[['gauge', 'Baseline vs. actual', 'Schedule and cost variance against the approved baseline.'],
            ['triangle-alert', 'Risk register', 'Ranked, owned, with mitigation dates.'],
            ['clipboard-check', 'Quality log', 'Inspections, NCRs and close-out status.'],
            ['shield-check', 'HSE record', 'Incidents, near-misses and toolbox coverage.'],
            ['coins', 'Cash flow', 'Certified, forecast and retention.'],
            ['file-text', 'Change control', 'Every variation, priced and dated.']].map(([ic, t, b], i) => (
              <Reveal key={t} delay={(i % 3) * 70}>
                <div style={{ display: 'flex', gap: 16 }}>
                  <TileP icon={ic} size={56} />
                  <div>
                    <div style={{ fontFamily: 'var(--font-heading)', fontWeight: 700, fontSize: 17 }}>{t}</div>
                    <div style={{ fontSize: 14, lineHeight: 1.6, color: 'var(--text-secondary)', marginTop: 6 }}>{b}</div>
                  </div>
                </div>
              </Reveal>
            ))}
        </div>
      </Section>

      <Section tone="page">
        <div style={{ display: 'flex', flexWrap: 'wrap', alignItems: 'flex-end', justifyContent: 'space-between', gap: 24, marginBottom: 36 }}>
          <div style={{ maxWidth: 720 }}>
            <div style={{ fontFamily: 'var(--font-label)', fontWeight: 700, fontSize: 11, letterSpacing: 'var(--tracking-widest)', textTransform: 'uppercase', color: 'var(--brand-yellow)' }}>Featured Clients</div>
            <h2 style={{ fontSize: 'clamp(24px,2.6vw,32px)', fontWeight: 700, letterSpacing: 'var(--tracking-tight)', margin: '12px 0 0' }}>The organisations behind these projects</h2>
          </div>
          <BtnP variant="outline" iconAfter="arrow-right" onClick={() => go('clients')}>Featured clients by sector</BtnP>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(160px,1fr))', gap: 16 }}>
          {DP.clientGroups.flatMap((g) => g.items).map((c, i) => (
            <Reveal key={c.name} delay={(i % 6) * 60}>
              <ClientP name={c.name} file={c.file} sector={c.note} height={88} base="./assets" />
            </Reveal>
          ))}
        </div>
      </Section>

      <ProjectDrawer p={open} onClose={() => setOpen(null)} />
    </div>
  );
}

function ClientsScreen({ go }) {
  return (
    <div>
      <PageHero eyebrow="Featured Clients" tone="brand"
        title="Trusted by Industry Leaders Across Multiple Sectors"
        lede="A selection of featured clients — healthcare groups, energy operators, fitness and entertainment brands and creative agencies across the UAE, KSA and Egypt. Full references available on request." />

      <Section tone="page">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 72 }}>
          {DP.clientGroups.map((g, gi) => (
            <div key={g.sector}>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 16, paddingBottom: 18, marginBottom: 28, borderBottom: '1px solid var(--border-default)' }}>
                <h3 style={{ fontSize: 26, fontWeight: 700, margin: 0, letterSpacing: 'var(--tracking-tight)' }}>{g.sector}</h3>
                <span style={{ fontFamily: 'var(--font-mono)', fontSize: 13, color: 'var(--text-muted)' }}>{String(g.items.length).padStart(2, '0')}</span>
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(220px,1fr))', gap: 24 }}>
                {g.items.map((c, i) => (
                  <Reveal key={c.name} delay={(i % 4) * 70}>
                    <div>
                      <ClientP name={c.name} file={c.file} sector={c.note} height={104} base="./assets" />
                      <div style={{ marginTop: 14 }}>
                        <div style={{ fontFamily: 'var(--font-heading)', fontWeight: 700, fontSize: 16 }}>{c.name}</div>
                        {c.note ? <div style={{ fontSize: 13, color: 'var(--text-muted)', marginTop: 4 }}>{c.note}</div> : null}
                      </div>
                    </div>
                  </Reveal>
                ))}
              </div>
            </div>
          ))}
        </div>
      </Section>

      <Section tone="card" pad={96}>
        <div style={{ display: 'flex', flexWrap: 'wrap', alignItems: 'center', justifyContent: 'space-between', gap: 28 }}>
          <div>
            <h2 style={{ fontSize: 'clamp(24px,2.6vw,32px)', fontWeight: 700, letterSpacing: 'var(--tracking-tight)', margin: 0 }}>See the work behind these names</h2>
            <p style={{ fontSize: 17, color: 'var(--text-secondary)', marginTop: 12 }}>Reference projects, sector by sector.</p>
          </div>
          <BtnP variant="primary" size="lg" iconAfter="arrow-right" onClick={() => go('projects')}>View reference projects</BtnP>
        </div>
      </Section>
    </div>
  );
}

Object.assign(window, { ProjectsScreen, ClientsScreen });
