/* global React, Nav */
const { useState: usePState, useMemo: usePMemo } = React;

/* =============================================================================
   Photo page — D6 nav pattern adapted for real photo collections.
   Sidebar drawer: search + featured pin row + scrollable list of all collections.
   Right pane: cover hero + frames grid for the active collection.
   Wrapped in robis brand chrome (Nav, dark header band, contact CTA).
============================================================================= */

const P_MONO  = { fontFamily: '"Montserrat", "Helvetica Neue", Arial, sans-serif', fontWeight: 500, letterSpacing: '.2em', textTransform: 'uppercase' };
const P_TITLE = { fontFamily: '"Montserrat", "Helvetica Neue", Arial, sans-serif', fontWeight: 700, letterSpacing: '.02em' };

const P_IMGS = [
  './assets/imagery/porsche-rally.jpg',
  './assets/imagery/m5.jpg',
  './assets/imagery/golf-r.jpg',
  './assets/imagery/golf-course.jpg',
  './assets/imagery/sky-tower.jpg',
];
const pimg = (i) => P_IMGS[i % P_IMGS.length];

/* Real-feeling photo collections */
const PHOTO_COLLECTIONS = [
  {
    slug: '01', title: 'Automotive', year: '2024', count: 42,
    cover: pimg(1), tag: 'Commercial', client: 'MK CAR RENTALS', pinned: true,
    description:
      'A year-long study of performance machinery — from studio showpieces to low-angle tarmac work. Shot across London, Silverstone, and a handful of private collections.',
    items: [
      { src: pimg(1), title: 'M5 Competition', date: 'FEB 2024', loc: 'STUDIO',     tag: 'Automotive' },
      { src: pimg(2), title: 'Nardo Golf R',    date: 'MAR 2024', loc: 'LONDON',     tag: 'Automotive' },
      { src: pimg(0), title: 'Paddock',         date: 'JAN 2024', loc: 'SILVERSTONE',tag: 'Portrait'   },
      { src: pimg(1), title: 'Low Angle',       date: 'FEB 2024', loc: 'STUDIO',     tag: 'Automotive' },
      { src: pimg(2), title: 'Urban Crop',      date: 'APR 2024', loc: 'LONDON',     tag: 'Editorial'  },
      { src: pimg(1), title: 'Showroom',        date: 'FEB 2024', loc: 'STUDIO',     tag: 'Commercial' },
      { src: pimg(0), title: 'Pit Portrait',    date: 'MAR 2024', loc: 'SILVERSTONE',tag: 'Portrait'   },
      { src: pimg(2), title: 'Cold Light',      date: 'JUN 2024', loc: 'STUDIO',     tag: 'Automotive' },
    ],
  },
  {
    slug: '02', title: 'Motorsport', year: '2024', count: 28,
    cover: pimg(0), tag: 'Editorial', client: 'INDEPENDENT SERIES', pinned: true,
    description:
      'Trackside across the summer season. Long lenses, short runs, and the small rituals between sessions — driver briefs, tyre pressures, and the last glance at telemetry before the flag drops.',
    items: [
      { src: pimg(0), title: 'Rally Porsche',   date: 'JAN 2024', loc: 'SNOWDONIA',  tag: 'Motorsport' },
      { src: pimg(0), title: 'GT3 In Motion',   date: 'FEB 2024', loc: 'SILVERSTONE',tag: 'Motorsport' },
      { src: pimg(1), title: 'Pit Lane',        date: 'FEB 2024', loc: 'SILVERSTONE',tag: 'Editorial'  },
      { src: pimg(2), title: 'Trackside',       date: 'MAR 2024', loc: 'DONINGTON',  tag: 'Motorsport' },
      { src: pimg(0), title: 'Starting Grid',   date: 'MAR 2024', loc: 'DONINGTON',  tag: 'Motorsport' },
    ],
  },
  {
    slug: '03', title: 'Lifestyle', year: '2023', count: 36,
    cover: pimg(3), tag: 'Editorial', client: 'PRIVATE COMMISSIONS', pinned: true,
    description:
      'Quiet hours. The cold edge of the morning on a fairway, a warm window in the Surrey Hills, a long afternoon in the Cotswolds. Work that leans away from the subject to let the weather do the talking.',
    items: [
      { src: pimg(3), title: 'Morning Fairway', date: 'NOV 2023', loc: 'SURREY',     tag: 'Lifestyle'  },
      { src: pimg(3), title: 'Fairway Light',   date: 'NOV 2023', loc: 'SURREY',     tag: 'Lifestyle'  },
      { src: pimg(0), title: 'Paddock Study',   date: 'OCT 2023', loc: 'LONDON',     tag: 'Portrait'   },
      { src: pimg(3), title: 'Afternoon',       date: 'SEP 2023', loc: 'COTSWOLDS',  tag: 'Lifestyle'  },
      { src: pimg(4), title: 'Last Light',      date: 'DEC 2023', loc: 'COTSWOLDS',  tag: 'Lifestyle'  },
    ],
  },
  {
    slug: '04', title: 'Architecture', year: '2023', count: 19,
    cover: pimg(4), tag: 'Editorial', client: 'FUTURE TENSE MAG', pinned: true,
    description:
      'London from inside its own weather. A tower, a glass curtain wall, a street-level reflection that reads like a second city. Built things measured against the hour they were shot in.',
    items: [
      { src: pimg(4), title: 'Tower at Altitude', date: 'OCT 2023', loc: 'LONDON',  tag: 'Architecture' },
      { src: pimg(4), title: 'City Currents',     date: 'OCT 2023', loc: 'LONDON',  tag: 'Architecture' },
      { src: pimg(4), title: 'Tower Studies',     date: 'SEP 2023', loc: 'LONDON',  tag: 'Architecture' },
      { src: pimg(4), title: 'Glass Curtain',     date: 'SEP 2023', loc: 'LONDON',  tag: 'Architecture' },
    ],
  },
  /* Additional collections — unfeatured, scrollable in sidebar */
  ...['Portrait', 'Studio', 'Silverstone', 'Cotswolds', 'Surrey Hills', 'Pit Lane',
      'Showroom', 'Last Light', 'Cold Mornings', 'Tarmac', 'Long Lens',
      'Late Summer', 'Winter Drives', 'Backroads', 'Quiet Hours', 'Night Run',
      'Heritage', 'Off Season', 'Weather', 'Private']
    .map((title, i) => {
      const idx = i + 4;
      const itemCount = 4 + (i % 5);
      const tags    = ['Portrait', 'Editorial', 'Lifestyle', 'Commercial', 'Automotive', 'Architecture'];
      const clients = ['NORTH ROAD CO', 'PADDOCK MEDIA', 'PRIVATE', 'MK CAR RENTALS', 'FUTURE TENSE'];
      const years   = ['2024', '2023', '2023', '2022'];
      const locs    = ['STUDIO', 'LONDON', 'SILVERSTONE', 'DONINGTON', 'COTSWOLDS', 'BEDFORD', 'SURREY'];
      return {
        slug: String(idx + 1).padStart(2, '0'),
        title,
        year: years[i % years.length],
        count: 12 + ((i * 7) % 60),
        cover: pimg(idx),
        tag: tags[i % tags.length],
        client: clients[i % clients.length],
        pinned: false,
        description:
          i % 2 === 0
            ? 'A long study held over months. Cold light, slow shutters, and a willingness to wait. Edited tight.'
            : 'Field work — moving fast, framing tight. Long lenses and short windows of weather.',
        items: Array.from({ length: itemCount }, (_, j) => ({
          src: pimg(idx + j),
          title: `${title} · 0${j + 1}`,
          date: `${['JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC'][(idx + j) % 12]} ${years[i % years.length]}`,
          loc: locs[(idx + j) % locs.length],
          tag: tags[(idx + j) % tags.length],
        })),
      };
    }),
];

/* ---------- Cover hero + frames grid (right pane) ---------- */
function PhotoHeroAndGrid({ col }) {
  const [hover, setHover] = usePState(null);
  return (
    <div key={'panel-' + col.slug} style={{ animation: 'pFade .5s cubic-bezier(.22,.61,.36,1) both' }}>
      {/* Hero — wide aspect, capped height so grid is visible on 16:9 */}
      <div style={{
        padding: '28px 36px 32px',
        display: 'grid',
        gridTemplateColumns: 'minmax(0, 1.6fr) minmax(280px, 1fr)',
        gap: 36, alignItems: 'stretch',
      }}>
        <div style={{
          position: 'relative', overflow: 'hidden', background: '#ddd',
          aspectRatio: '16 / 9',
          maxHeight: 'calc(100vh - 220px)',
        }}>
          <img src={col.cover} alt={col.title}
            style={{ width: '100%', height: '100%', objectFit: 'cover', filter: 'grayscale(.15)' }} />
          <div style={{
            position: 'absolute', left: 16, top: 16,
            ...P_MONO, fontSize: 10, color: '#0a0a0b',
            padding: '6px 10px', background: 'rgba(255,255,255,.85)', backdropFilter: 'blur(6px)',
          }}>Collection · {col.slug}</div>
          {col.pinned && (
            <div style={{
              position: 'absolute', right: 16, top: 16,
              ...P_MONO, fontSize: 9, color: '#fff',
              padding: '5px 9px', background: '#7993AC',
            }}>Featured</div>
          )}
        </div>
        <div style={{
          display: 'flex', flexDirection: 'column', justifyContent: 'space-between',
          paddingTop: 4,
        }}>
          <div>
            <div style={{ ...P_MONO, fontSize: 10, color: '#7993AC' }}>{col.client} · {col.year}</div>
            <h2 style={{
              ...P_TITLE, fontSize: 'clamp(28px, 2.6vw, 40px)',
              lineHeight: 1.05, textTransform: 'uppercase',
              margin: '8px 0 16px', color: '#0a0a0b',
            }}>
              {col.title}<span style={{ color: '#7993AC' }}>.</span>
            </h2>
            <p style={{
              fontFamily: '"Montserrat", "Helvetica Neue", Arial, sans-serif', fontWeight: 400,
              fontSize: 13, lineHeight: 1.6, color: 'rgba(10,10,11,.72)', margin: 0,
              textWrap: 'pretty',
            }}>{col.description}</p>
          </div>
          <div style={{
            display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 16,
            marginTop: 20, paddingTop: 18,
            borderTop: '1px solid rgba(10,10,11,.08)',
          }}>
            {[['Frames', col.count], ['Category', col.tag], ['Year', col.year]].map(([k, v]) => (
              <div key={k}>
                <div style={{ ...P_MONO, fontSize: 9, color: '#7993AC' }}>{k}</div>
                <div style={{ ...P_TITLE, fontSize: 18, marginTop: 4, color: '#0a0a0b' }}>{v}</div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Grid */}
      <div style={{ borderTop: '1px solid rgba(10,10,11,.1)' }}>
        <div style={{ padding: '20px 36px 12px', display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
          <h3 style={{ ...P_TITLE, fontSize: 16, textTransform: 'uppercase', margin: 0, color: '#0a0a0b' }}>
            All frames<span style={{ color: '#7993AC' }}>.</span>
          </h3>
          <div style={{ ...P_MONO, fontSize: 10, color: '#7993AC' }}>{col.items.length} of {col.count}</div>
        </div>
        <div style={{
          padding: '0 36px 48px',
          display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(200px, 1fr))', gap: 6,
        }}>
          {col.items.map((it, i) => {
            const h = hover === i;
            return (
              <div key={i}
                onMouseEnter={() => setHover(i)}
                onMouseLeave={() => setHover(null)}
                style={{ position: 'relative', overflow: 'hidden', aspectRatio: '4 / 5', background: '#ddd', cursor: 'pointer' }}>
                <img src={it.src} alt="" loading="lazy"
                  style={{
                    width: '100%', height: '100%', objectFit: 'cover',
                    filter: h ? 'grayscale(0)' : 'grayscale(1) brightness(.92)',
                    transform: h ? 'scale(1.04)' : 'scale(1)',
                    transition: 'transform 1s cubic-bezier(.2,.7,.15,1), filter .4s',
                  }} />
                <div style={{
                  position: 'absolute', left: 10, top: 10,
                  ...P_MONO, fontSize: 9, color: '#0a0a0b',
                  padding: '4px 7px', background: 'rgba(255,255,255,.85)', backdropFilter: 'blur(4px)',
                }}>0{i + 1}</div>
                <div style={{
                  position: 'absolute', left: 12, right: 12, bottom: 12,
                  ...P_MONO, fontSize: 9, color: '#fff',
                  textShadow: '0 1px 6px rgba(0,0,0,.5)',
                  opacity: h ? 1 : 0,
                  transform: h ? 'translateY(0)' : 'translateY(4px)',
                  transition: 'opacity .25s, transform .25s',
                }}>{it.title} · {it.loc}</div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

/* ---------- Sidebar row ---------- */
function PSidebarRow({ c, isActive, onClick }) {
  return (
    <div onClick={onClick}
      style={{
        display: 'grid', gridTemplateColumns: '40px 1fr auto',
        gap: 12, alignItems: 'center',
        padding: '8px 16px', cursor: 'pointer',
        background: isActive ? '#0a0a0b' : 'transparent',
        color: isActive ? '#fff' : '#0a0a0b',
        transition: 'background .2s, color .2s',
      }}>
      <div style={{ width: 40, height: 30, overflow: 'hidden', position: 'relative', flex: '0 0 auto' }}>
        <img src={c.cover} alt=""
          style={{
            width: '100%', height: '100%', objectFit: 'cover',
            filter: isActive ? 'none' : 'grayscale(1) brightness(.92)',
          }} />
        {c.pinned && (
          <div style={{
            position: 'absolute', right: 2, top: 2,
            width: 6, height: 6, background: '#7993AC',
          }} />
        )}
      </div>
      <div style={{ minWidth: 0 }}>
        <div style={{
          ...P_TITLE, fontSize: 12, textTransform: 'uppercase',
          whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
        }}>{c.title}</div>
        <div style={{ ...P_MONO, fontSize: 8, opacity: .55, marginTop: 2 }}>
          {c.slug} · {c.year} · {c.tag}
        </div>
      </div>
      <div style={{ ...P_MONO, fontSize: 8, opacity: .55 }}>{c.count}f</div>
    </div>
  );
}

/* ---------- Photo page ---------- */
function PhotoPortfolio({ onNav }) {
  const [active, setActive] = usePState(0);
  const [open, setOpen] = usePState(true);
  const [q, setQ] = usePState('');
  const col = PHOTO_COLLECTIONS[active];
  const featured = usePMemo(() => PHOTO_COLLECTIONS.filter((c) => c.pinned), []);
  const others = usePMemo(() => PHOTO_COLLECTIONS.filter((c) => !c.pinned), []);
  const matches = q
    ? PHOTO_COLLECTIONS.filter((c) =>
        c.title.toLowerCase().includes(q.toLowerCase()) ||
        c.tag.toLowerCase().includes(q.toLowerCase()) ||
        c.client.toLowerCase().includes(q.toLowerCase())
      )
    : null;

  const w = open ? 360 : 64;

  return (
    <section style={{ minHeight: '100vh', background: '#fff', color: '#0a0a0b', position: 'relative' }}>
      <Nav current="Photo" onNav={onNav} onDark={false} />

      {/* Full-bleed divider under nav, then sidebar+content share the surface */}
      <div style={{
        position: 'absolute', top: 112, left: 0, right: 0,
        borderBottom: '1px solid rgba(10,10,11,.08)',
      }} />

      {/* Sidebar + content — sidebar tucked under nav, no header band, no breadcrumb */}
      <div className="slideUp" style={{
        display: 'grid', gridTemplateColumns: `${w}px 1fr`,
        transition: 'grid-template-columns .35s cubic-bezier(.7,0,.2,1)',
        paddingTop: 113,
        animationDelay: '0.05s',
      }}>
        {/* Sidebar */}
        <div style={{
          borderRight: '1px solid rgba(10,10,11,.08)',
          display: 'flex', flexDirection: 'column',
          overflow: 'hidden',
          background: '#fff',
          minHeight: 800,
        }}>
          {/* Header — minimal: just collection count + collapse, aligns with nav rhythm */}
          <div style={{
            padding: open ? '22px 20px 18px' : '22px 0',
            display: 'flex', alignItems: 'center',
            justifyContent: open ? 'space-between' : 'center',
          }}>
            {open && (
              <div style={{ ...P_MONO, fontSize: 10, color: 'rgba(10,10,11,.55)' }}>
                {PHOTO_COLLECTIONS.length} Collections
              </div>
            )}
            <div onClick={() => setOpen(!open)}
              style={{
                width: 22, height: 22, cursor: 'pointer',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                ...P_MONO, fontSize: 14, color: '#0a0a0b',
              }}>{open ? '‹' : '›'}</div>
          </div>

          {open && (
            <>
              {/* Search */}
              <div style={{ padding: '14px 16px 10px', position: 'relative' }}>
                <input
                  value={q}
                  onChange={(e) => setQ(e.target.value)}
                  placeholder="Search collections…"
                  style={{
                    width: '100%', padding: '10px 12px 10px 34px',
                    border: '1px solid rgba(10,10,11,.18)',
                    background: '#fff',
                    fontFamily: '"Montserrat", Arial, sans-serif', fontWeight: 500,
                    fontSize: 12, letterSpacing: '.05em', color: '#0a0a0b',
                    outline: 'none', boxSizing: 'border-box',
                  }}
                />
                <div style={{
                  position: 'absolute', left: 28, top: '50%', transform: 'translateY(-50%)',
                  ...P_MONO, fontSize: 12, color: '#7993AC',
                }}>⌕</div>
              </div>

              <div style={{ overflowY: 'auto', flex: 1, paddingBottom: 12, maxHeight: 720 }}>
                {matches !== null ? (
                  <>
                    <div style={{ padding: '12px 16px 8px', ...P_MONO, fontSize: 9, color: '#7993AC' }}>
                      {matches.length} {matches.length === 1 ? 'Match' : 'Matches'}
                    </div>
                    {matches.length === 0 && (
                      <div style={{ padding: '8px 16px', ...P_MONO, fontSize: 10, color: 'rgba(10,10,11,.45)' }}>
                        No collections found.
                      </div>
                    )}
                    {matches.map((c) => {
                      const i = PHOTO_COLLECTIONS.indexOf(c);
                      return (
                        <PSidebarRow key={c.slug} c={c} isActive={active === i} onClick={() => setActive(i)} />
                      );
                    })}
                  </>
                ) : (
                  <>
                    {/* Featured */}
                    <div style={{ padding: '12px 16px 8px', ...P_MONO, fontSize: 9, color: '#7993AC' }}>
                      ★ Featured
                    </div>
                    <div style={{
                      padding: '0 16px 14px',
                      display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8,
                    }}>
                      {featured.map((c) => {
                        const i = PHOTO_COLLECTIONS.indexOf(c);
                        const isActive = active === i;
                        return (
                          <div key={c.slug} onClick={() => setActive(i)}
                            style={{
                              position: 'relative', cursor: 'pointer',
                              aspectRatio: '5 / 4', overflow: 'hidden',
                              outline: isActive ? '2px solid #0a0a0b' : '2px solid transparent',
                              outlineOffset: -2, background: '#ddd',
                            }}>
                            <img src={c.cover} alt=""
                              style={{
                                width: '100%', height: '100%', objectFit: 'cover',
                                filter: isActive ? 'grayscale(0)' : 'grayscale(1) brightness(.92)',
                                transition: 'filter .35s',
                              }} />
                            <div style={{
                              position: 'absolute', inset: 0,
                              background: 'linear-gradient(180deg, transparent 50%, rgba(0,0,0,.6))',
                            }} />
                            <div style={{ position: 'absolute', left: 8, bottom: 6, right: 8 }}>
                              <div style={{ ...P_MONO, fontSize: 7, color: '#fff' }}>{c.slug}</div>
                              <div style={{
                                ...P_TITLE, fontSize: 11, color: '#fff', textTransform: 'uppercase',
                                whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
                              }}>{c.title}</div>
                            </div>
                          </div>
                        );
                      })}
                    </div>

                    {/* All */}
                    <div style={{
                      padding: '8px 16px', ...P_MONO, fontSize: 9, color: '#7993AC',
                      borderTop: '1px solid rgba(10,10,11,.06)',
                    }}>All Collections</div>
                    {others.map((c) => {
                      const i = PHOTO_COLLECTIONS.indexOf(c);
                      return (
                        <PSidebarRow key={c.slug} c={c} isActive={active === i} onClick={() => setActive(i)} />
                      );
                    })}
                  </>
                )}
              </div>
            </>
          )}

          {!open && (
            <div style={{ overflowY: 'auto', flex: 1, padding: '6px 0' }}>
              {PHOTO_COLLECTIONS.map((c, i) => {
                const isActive = active === i;
                return (
                  <div key={c.slug} onClick={() => setActive(i)}
                    style={{
                      padding: '6px 12px', cursor: 'pointer',
                      background: isActive ? '#0a0a0b' : 'transparent',
                    }}>
                    <div style={{ width: 40, height: 30, overflow: 'hidden', position: 'relative' }}>
                      <img src={c.cover} alt=""
                        style={{
                          width: '100%', height: '100%', objectFit: 'cover',
                          filter: isActive ? 'none' : 'grayscale(1) brightness(.92)',
                        }} />
                      {c.pinned && (
                        <div style={{
                          position: 'absolute', right: 2, top: 2,
                          width: 6, height: 6, background: '#7993AC',
                        }} />
                      )}
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>

        {/* Right pane */}
        <div>
          <PhotoHeroAndGrid col={col} />
        </div>
      </div>

      {/* Bottom CTA */}
      <div style={{
        padding: '40px 24px 96px',
        borderTop: '1px solid rgba(10,10,11,.08)',
        textAlign: 'center',
      }}>
        <div style={{
          ...P_TITLE, fontSize: 22, letterSpacing: '.04em',
          textTransform: 'uppercase', marginBottom: 18, color: '#0a0a0b',
        }}>Got a story to tell?</div>
        <a onClick={() => onNav('Contact Us')} style={{
          display: 'inline-block', cursor: 'pointer',
          padding: '14px 34px', borderRadius: 999,
          background: '#0a0a0b', color: '#fff',
          fontFamily: '"Montserrat", "Helvetica Neue", Arial, sans-serif',
          fontWeight: 700, fontSize: 13, letterSpacing: '.14em',
          textTransform: 'uppercase',
        }}>Contact Us</a>
      </div>

      <style>{`@keyframes pFade { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: translateY(0); } }`}</style>
    </section>
  );
}

Object.assign(window, { PhotoPortfolio });
