// StudioPage.jsx — PROYECTO Studio Detail Page

const STUDIO_DATA = {
  studio01: {
    num: '01',
    name: 'PREMIUM',
    titleLine1: '01 — PRE-VIZ',
    titleLine2: 'PREMIUM',
    line1Color: '#ffffff',
    line2Color: 'var(--accent, #e6351e)',
    tagline: 'The highest quality pre-visualization infrastructure.',
    description: 'Purpose-built for lighting designers running Depence, MA3, and related pre-visualization software. Used by LD teams working for artists at the highest level of touring production.',
    specs: [
      ['SOFTWARE',      'DEPENCE / MA3 / WYSIWYG'],
      ['NETWORKING',    'ArtNET / sACN / NDI'],
      ['POWER',         '200A DISTRO'],
      ['BLACKOUT',      'FULLY BLACKOUT CAPABLE'],
      ['WORKSTATIONS',  'HIGH-SPEC RENDERING RIGS'],
      ['ACCESS',        'BY APPOINTMENT'],
      ['AVAILABILITY',  'DAILY / WEEKLY'],
    ],
  },
  studio02: {
    num: '02',
    name: 'STANDARD',
    titleLine1: '02 — PRE-VIZ',
    titleLine2: 'STANDARD',
    line1Color: '#ffffff',
    line2Color: 'var(--accent, #e6351e)',
    tagline: 'Professional-grade pre-visualization at a lower price point.',
    description: 'MA3 compatible, blackout capable, networked. Built for LDs who need a serious working environment while looking to save costs.',
    specs: [
      ['SOFTWARE',      'MA3 / DEPENCE COMPATIBLE'],
      ['NETWORKING',    'ArtNET / sACN'],
      ['POWER',         '100A DISTRO'],
      ['BLACKOUT',      'FULLY BLACKOUT CAPABLE'],
      ['WORKSTATIONS',  'STANDARD RENDERING SETUP'],
      ['ACCESS',        'BY APPOINTMENT'],
      ['AVAILABILITY',  'DAILY / WEEKLY'],
    ],
  },
  studio03: {
    num: '03',
    name: 'REHEARSAL /EVENT',
    titleLine1: '03 —',
    titleLine2: 'REHEARSAL /EVENT',
    line1Color: '#ffffff',
    line2Color: 'var(--accent, #e6351e)',
    tagline: 'Built for artists and brands operating at a high level.',
    description: 'Full rehearsal infrastructure for touring artists and production teams. Designed by someone who has built and toured shows at scale. That expertise is embedded in the space.',
    specs: [
      ['SQUARE FOOTAGE', '6,000 SQ FT'],
      ['CEILING HEIGHT', '24 FT'],
      ['CDJS',           'PIONEER CDJ-3000X'],
      ['AUDIO',          'Pioneer DJ VM-70 SPEAKERS'],
      ['VISUAL',         'HIGH-FIDELITY MONITORS'],
      ['ACCESS',         'BY APPOINTMENT'],
      ['AVAILABILITY',   'DAILY / WEEKLY'],
    ],
  },
};

// Scramble-on-hover for spec values
const ScrambleText = ({ text }) => {
  const [display, setDisplay] = React.useState(text);
  const animRef = React.useRef(null);
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';

  const scramble = () => {
    if (animRef.current) clearInterval(animRef.current);
    let step = 0; const steps = 8;
    animRef.current = setInterval(() => {
      step++;
      const out = text.split('').map((ch, i) => {
        if (ch === ' ' || ch === '/' || ch === '·') return ch;
        const locked = step >= (i + 1) * (steps / text.length);
        return locked ? ch : chars[Math.floor(Math.random() * chars.length)];
      }).join('');
      setDisplay(out);
      if (step >= steps + 2) { clearInterval(animRef.current); setDisplay(text); }
    }, 35);
  };

  return <span onMouseEnter={scramble} style={{ cursor: 'none' }}>{display}</span>;
};

// Character-by-character reveal
const RevealText = ({ text, color, delay = 0 }) => {
  const [visibleCount, setVisibleCount] = React.useState(0);
  React.useEffect(() => {
    setVisibleCount(0);
    let i = 0;
    const t = setTimeout(() => {
      const interval = setInterval(() => {
        i++;
        setVisibleCount(i);
        if (i >= text.length) clearInterval(interval);
      }, 38);
      return () => clearInterval(interval);
    }, delay);
    return () => clearTimeout(t);
  }, [text, delay]);

  return (
    <span style={{ color }}>
      {text.split('').map((ch, i) => (
        <span key={i} style={{
          opacity: i < visibleCount ? 1 : 0,
          transition: 'opacity 60ms linear',
          display: 'inline-block',
          width: ch === ' ' ? '0.3em' : 'auto',
        }}>{ch}</span>
      ))}
    </span>
  );
};

const StudioPage = ({ studioId, onNavigate, clearance = 'low' }) => {
  const cmsContent = (typeof useCMSContent === 'function') ? useCMSContent() : null;
  const studio = (cmsContent && cmsContent.studios && cmsContent.studios[studioId]) || STUDIO_DATA[studioId];
  const isLowClearance = clearance !== 'high';
  // How many spec rows are visible at low clearance — defaults to 2.
  const publicSpecCount = (typeof studio.publicSpecCount === 'number')
    ? Math.max(0, Math.min(studio.specs.length, studio.publicSpecCount))
    : 2;
  const [visible, setVisible] = React.useState(false);
  const [typedSpecs, setTypedSpecs] = React.useState(0);
  const [titleKey, setTitleKey] = React.useState(0);
  const [imgFailed, setImgFailed] = React.useState(false);
  const [isMobile, setIsMobile] = React.useState(!!window.__IS_MOBILE);

  React.useEffect(() => {
    if (typeof window.__onMobileChange === 'function') {
      return window.__onMobileChange(setIsMobile);
    }
  }, []);

  React.useEffect(() => {
    setVisible(false);
    setTypedSpecs(0);
    setTitleKey(k => k + 1);
    setImgFailed(false);
    const t1 = setTimeout(() => setVisible(true), 60);
    let n = 0;
    const interval = setInterval(() => {
      n += 1;
      setTypedSpecs(n);
      if (!studio || n >= studio.specs.length) clearInterval(interval);
    }, 70);
    return () => { clearTimeout(t1); clearInterval(interval); };
  }, [studioId]);

  if (!studio) return null;

  // Data-driven two-line title system
  // titleLine1 / titleLine2 + line1Color / line2Color from content.json
  // Falls back gracefully if new fields not present
  const line1  = studio.titleLine1 || (studio.num + ' —');
  const line2  = studio.titleLine2 || studio.name;
  const color1 = studio.line1Color || '#ffffff';
  const color2 = studio.line2Color || 'var(--accent, #e6351e)';

  // Delay math for character reveal
  const numDelay   = 80;
  const line2Delay = numDelay + line1.length * 38 + 60;

  // Dynamic font size — shrinks proportionally for longer titles
  // "PREMIUM" = 7 chars → full size, "REHEARSAL /EVENT" = 16 chars → smaller
  const maxChars = Math.max(line1.length, line2.length);
  const titleFontSize = maxChars <= 8
    ? 'clamp(28px, 4.2vw, 64px)'
    : maxChars <= 12
    ? 'clamp(24px, 3.4vw, 52px)'
    : 'clamp(20px, 2.6vw, 40px)';

  return (
    <div style={{ ...ss.page, opacity: visible ? 1 : 0 }}>

      {/* ── Title ── */}
      <div style={{
        ...ss.titleBlock,
        ...(isMobile ? { padding: '28px 20px 0' } : {}),
        ...(isLowClearance ? { filter: 'grayscale(1)' } : {}),
      }}>
        <div style={{
          ...ss.bgNum,
          ...(isMobile ? { fontSize: 120, top: 0, left: 12 } : {}),
        }}>{studio.num}</div>
        <div style={{
          ...ss.titleRow,
          ...(isMobile ? {
            flexDirection: 'column', alignItems: 'flex-start',
            gap: 20, paddingBottom: 20,
          } : {}),
        }}>
          <div style={ss.titleStack} key={titleKey}>
            {/* Line 1 */}
            <div style={{
              ...ss.title,
              fontSize: isMobile ? 'clamp(18px, 5.5vw, 28px)' : titleFontSize,
            }}>
              <RevealText text={line1} color={color1} delay={numDelay} />
            </div>
            {/* Line 2 — allows wrap on mobile so long titles like "REHEARSAL /EVENT" break at the space */}
            <div style={{
              ...ss.titleLine2,
              fontSize: isMobile ? 'clamp(18px, 5.5vw, 28px)' : titleFontSize,
              ...(isMobile ? { whiteSpace: 'normal' } : {}),
            }}>
              <RevealText text={line2} color={color2} delay={line2Delay} />
            </div>
          </div>
          <div style={{
            ...ss.titleMeta,
            ...(isMobile ? { textAlign: 'left', paddingBottom: 0 } : {}),
          }}>
            <div style={ss.studioLabel}>PROYECTO {studio.num}</div>
            <div style={{
              ...ss.tagline,
              ...(isMobile ? { textAlign: 'left', maxWidth: '100%', fontSize: 13 } : {}),
            }}>{studio.tagline}</div>
          </div>
        </div>
        <div style={ss.titleRule} />
      </div>

      {/* ── Overview (full width) ── */}
      <div style={{
        ...ss.overviewRow,
        ...(isMobile ? { padding: '28px 20px' } : {}),
        ...(isLowClearance ? { filter: 'grayscale(1)' } : {}),
      }}>
        <div style={ss.overviewLeft}>
          <div style={{...ss.sectionLabel, color: studio.overviewLabelColor || 'var(--accent, #e6351e)'}}>{studio.overviewLabel || 'OVERVIEW'}</div>
          <div style={{
            ...ss.description,
            ...(isMobile ? { fontSize: 14, lineHeight: 1.7 } : {}),
          }}>{studio.description}</div>
        </div>
      </div>

      {/* ── Photo + Specs pillar ── */}
      <div style={{
        ...ss.mainRow,
        ...(isMobile ? {
          gridTemplateColumns: '1fr',
          gap: 24,
          padding: '28px 20px',
        } : {}),
      }}>
        {/* Photo wrapper — holds the photo (which gets blurred at low clearance) and the badge (which doesn't) */}
        <div style={{
          ...ss.photoWrap,
          ...(isMobile ? { minHeight: 280 } : {}),
        }}>
          <div style={{
            ...ss.photo,
            position: 'absolute', inset: 0,
            ...((studio.image && !imgFailed)
              ? { backgroundImage: `url(${studio.image})`, backgroundSize: 'contain', backgroundPosition: 'center', backgroundRepeat: 'no-repeat' }
              : {}),
            ...(isLowClearance && studio.image && !imgFailed ? { filter: 'blur(22px) grayscale(1) brightness(0.7)' } : {}),
          }}>
            {(studio.image && !imgFailed) && (
              <img src={studio.image} onError={() => setImgFailed(true)} style={{ display: 'none' }} alt="" />
            )}
            {(!studio.image || imgFailed) && (<>
              <div style={{ ...ss.photoCorner, top: 16, left: 16, borderTop: '1px solid #1e1e1e', borderLeft: '1px solid #1e1e1e' }} />
              <div style={{ ...ss.photoCorner, top: 16, right: 16, borderTop: '1px solid #1e1e1e', borderRight: '1px solid #1e1e1e' }} />
              <div style={{ ...ss.photoCorner, bottom: 16, left: 16, borderBottom: '1px solid #1e1e1e', borderLeft: '1px solid #1e1e1e' }} />
              <div style={{ ...ss.photoCorner, bottom: 16, right: 16, borderBottom: '1px solid #1e1e1e', borderRight: '1px solid #1e1e1e' }} />
              <div style={ss.photoGrid} />
              <div style={ss.photoInner}>
                <div style={ss.photoLabel}>PROYECTO {studio.num} · {studio.name}</div>
                <div style={ss.photoSub}>[ photography pending ]</div>
                <div style={ss.photoCoords}>34.0522° N · 118.2437° W</div>
              </div>
            </>)}
          </div>
          {/* Clearance badge — absolutely positioned over photo, NOT inside the blur filter */}
          {isLowClearance && studio.image && !imgFailed && (
            <div style={ss.clearanceBadge}>
              <div style={ss.clearanceBadgeLine}>━ CLEARANCE REQUIRED ━</div>
              <div style={ss.clearanceBadgeSub}>level 02 access · contact for keys</div>
            </div>
          )}
        </div>

        {/* Specs pillar — right */}
        <div style={{
          ...ss.specsPillar,
          ...(isLowClearance ? { filter: 'grayscale(1)' } : {}),
        }}>
          <div style={{...ss.sectionLabel, color: studio.specsLabelColor || 'var(--accent, #e6351e)', marginBottom: 16}}>{studio.specsLabel || 'SPECIFICATIONS'}</div>
          <div style={ss.pillarList}>
            {studio.specs.map(([key, val], i) => {
              const redacted = isLowClearance && i >= publicSpecCount;
              // Generate a redaction bar of similar length to the real value (caps at 18 blocks)
              const barLen = Math.min(18, Math.max(8, Math.round((val || '').length * 0.7)));
              const redactedVal = '█'.repeat(barLen);
              return (
                <div
                  key={key}
                  style={{
                    ...ss.pillarRow,
                    opacity: i < typedSpecs ? 1 : 0,
                    transform: i < typedSpecs ? 'translateX(0)' : 'translateX(-8px)',
                    transitionDelay: `${i * 45}ms`,
                    borderLeft: i < typedSpecs ? `1px solid ${redacted ? '#3a3a3a' : 'var(--accent, #e6351e)'}` : '1px solid transparent',
                  }}
                >
                  <div style={{...ss.pillarKey, ...(redacted ? { color: '#3a3a3a' } : {})}}>{key}</div>
                  <div style={{...ss.pillarVal, ...(redacted ? ss.pillarValRedacted : {})}}>
                    {redacted ? redactedVal : <ScrambleText text={val} />}
                  </div>
                </div>
              );
            })}
          </div>
          {/* Footer hint when content is redacted */}
          {isLowClearance && publicSpecCount < studio.specs.length && (
            <div style={ss.specsRedactedHint}>
              ━ {studio.specs.length - publicSpecCount} ITEMS CLASSIFIED ━
            </div>
          )}
        </div>
      </div>

      {/* ── Access / CTA (full width bottom) ── */}
      <div style={{
        ...ss.accessSection,
        ...(isMobile ? { padding: '32px 20px 40px' } : {}),
        ...(isLowClearance ? { filter: 'grayscale(1)' } : {}),
      }}>
        <div style={{...ss.sectionLabel, color: studio.accessLabelColor || 'var(--accent, #e6351e)', textAlign: 'center', marginBottom: 16}}>{studio.accessLabel || 'ACCESS'}</div>
        <div style={{...ss.availLine, color: studio.requestAccessColor || '#ffffff', justifyContent: 'center', marginBottom: 24,
          ...(isMobile ? { fontSize: 11, letterSpacing: '0.12em' } : {})}}>
          <span style={ss.availArrow}>&gt;</span>
          <span>{studio.requestAccessText || 'REQUEST ACCESS'}</span>
          <span style={ss.blockCursor} />
        </div>
        <button
          style={{...ss.ctaBtn,
            color: studio.inquireBtnColor || 'var(--accent, #e6351e)',
            borderColor: studio.inquireBtnColor || 'var(--accent, #e6351e)',
            ...(isMobile ? { padding: '16px 44px', fontSize: 12, cursor: 'pointer' } : {}),
          }}
          onClick={() => onNavigate && onNavigate('contact')}
          onMouseEnter={(e) => { if (!isMobile) { e.currentTarget.style.background = studio.inquireBtnColor || 'var(--accent, #e6351e)'; e.currentTarget.style.color = '#000'; } }}
          onMouseLeave={(e) => { if (!isMobile) { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = studio.inquireBtnColor || 'var(--accent, #e6351e)'; } }}
        >
          {studio.inquireBtnText || 'INQUIRE ▸'}
        </button>
      </div>

      {/* ── Footer ── */}
      <div style={{
        ...ss.footerBar,
        ...(isMobile ? { padding: '24px 20px 32px', marginTop: 24, fontSize: 8 } : {}),
        ...(isLowClearance ? { filter: 'grayscale(1)' } : {}),
      }}>
        <span>PROYECTO</span>
        <span style={{ color: '#2a2a2a' }}>LOS ANGELES · {(cmsContent && cmsContent.global && cmsContent.global.footerYear) || '2025'}</span>
      </div>
    </div>
  );
};

const ss = {
  page: {
    minHeight: '100vh', background: '#050402',
    paddingTop: 48, fontFamily: "'Share Tech Mono', monospace",
    transition: 'opacity 200ms linear', color: '#fff',
  },

  /* Title */
  titleBlock: {
    padding: '48px 48px 0',
    position: 'relative', overflow: 'hidden',
  },
  bgNum: {
    position: 'absolute', top: -10, left: 28,
    fontFamily: "'Cindie2', sans-serif",
    fontSize: 220, fontWeight: 700,
    color: 'rgba(255,255,255,0.025)',
    lineHeight: 1, letterSpacing: '-0.02em',
    pointerEvents: 'none', userSelect: 'none', zIndex: 0,
  },
  titleRow: {
    display: 'flex', alignItems: 'flex-end',
    justifyContent: 'space-between',
    position: 'relative', zIndex: 1, paddingBottom: 24,
    gap: 32, flexWrap: 'nowrap',
  },
  titleStack: {
    display: 'flex', flexDirection: 'column',
    gap: 0, lineHeight: 1,
    minWidth: 0, flexShrink: 0,
  },
  title: {
    fontFamily: "'Cindie2', sans-serif",
    fontSize: 'clamp(20px, 2.8vw, 44px)',
    fontWeight: 700,
    letterSpacing: '0.02em', textTransform: 'uppercase',
    lineHeight: 1,
    whiteSpace: 'nowrap',
  },
  titleLine2: {
    fontFamily: "'Cindie2', sans-serif",
    fontSize: 'clamp(20px, 2.8vw, 44px)',
    fontWeight: 700,
    letterSpacing: '0.02em', textTransform: 'uppercase',
    lineHeight: 1.05,
    whiteSpace: 'nowrap',
  },
  titleMeta: { textAlign: 'right', paddingBottom: 4 },
  studioLabel: {
    fontSize: 10, color: 'var(--accent, #e6351e)',
    letterSpacing: '0.22em', textTransform: 'uppercase', marginBottom: 6,
  },
  tagline: {
    fontSize: 12, color: '#555', letterSpacing: '0.04em',
    fontFamily: "'Neogrotesk Pro', 'Helvetica Neue', sans-serif",
    maxWidth: 320, textAlign: 'right',
  },
  titleRule: {
    height: 1,
    background: 'linear-gradient(90deg, var(--accent, #e6351e) 0%, #333 40%, transparent 100%)',
    position: 'relative', zIndex: 1,
  },

  /* Overview — full width */
  overviewRow: {
    padding: '40px 48px', 
    borderBottom: '1px solid #0e0e0e',
  },
  overviewLeft: { maxWidth: 900 },
  sectionLabel: {
    fontSize: 9, color: 'var(--accent, #e6351e)',
    letterSpacing: '0.28em', textTransform: 'uppercase', marginBottom: 14,
  },
  description: {
    fontSize: 15, color: '#9a8f84', lineHeight: 1.9, letterSpacing: '0.025em',
    fontFamily: "'Neogrotesk Pro', 'Helvetica Neue', sans-serif",
  },
  availLine: {
    display: 'flex', alignItems: 'center', gap: 10,
    fontSize: 12, color: '#fff',
    letterSpacing: '0.16em', textTransform: 'uppercase',
  },
  availArrow: { color: 'var(--accent, #e6351e)' },
  blockCursor: {
    display: 'inline-block', width: 8, height: 12,
    background: 'var(--accent, #e6351e)', animation: 'blink 1.1s step-end infinite',
  },
  ctaBtn: {
    background: 'transparent', border: '1px solid var(--accent, #e6351e)',
    fontFamily: "'Share Tech Mono', monospace",
    fontSize: 11, letterSpacing: '0.22em', textTransform: 'uppercase',
    color: 'var(--accent, #e6351e)', padding: '14px 36px',
    transition: 'background 120ms linear, color 120ms linear',
    borderRadius: 0, cursor: 'none',
  },

  /* Main row — photo left, specs pillar right */
  mainRow: {
    display: 'grid',
    gridTemplateColumns: '1.85fr 1fr',
    gap: 32,
    padding: '48px 48px',
    alignItems: 'stretch',
  },

  /* Photo */
  photoWrap: {
    minHeight: 560,
    position: 'relative', overflow: 'hidden',
    border: '1px solid #0e0e0e', background: '#040404',
  },
  photo: {
    minHeight: 560,
    background: '#040404',
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    position: 'relative', overflow: 'hidden',
  },
  clearanceBadge: {
    position: 'absolute', inset: 0,
    display: 'flex', flexDirection: 'column',
    alignItems: 'center', justifyContent: 'center',
    gap: 10, pointerEvents: 'none',
    background: 'rgba(0,0,0,0.35)',
    zIndex: 2,
  },
  clearanceBadgeLine: {
    fontFamily: "'Share Tech Mono', monospace",
    fontSize: 13, color: 'var(--accent, #e6351e)',
    letterSpacing: '0.28em', textTransform: 'uppercase',
    textShadow: '0 0 10px rgba(230,53,30,0.5)',
  },
  clearanceBadgeSub: {
    fontFamily: "'Share Tech Mono', monospace",
    fontSize: 10, color: '#888',
    letterSpacing: '0.18em', textTransform: 'lowercase',
  },
  photoCorner: { position: 'absolute', width: 20, height: 20 },
  photoGrid: {
    position: 'absolute', inset: 0, pointerEvents: 'none',
    backgroundImage: 'linear-gradient(rgba(255,255,255,0.012) 1px, transparent 1px), linear-gradient(90deg, rgba(255,255,255,0.012) 1px, transparent 1px)',
    backgroundSize: '60px 60px',
  },
  photoInner: { textAlign: 'center', position: 'relative', zIndex: 1 },
  photoLabel: {
    fontSize: 10, color: '#2a2a2a',
    letterSpacing: '0.24em', textTransform: 'uppercase', marginBottom: 8,
  },
  photoSub: { fontSize: 10, color: '#1a1a1a', letterSpacing: '0.1em', marginBottom: 12 },
  photoCoords: { fontSize: 9, color: '#1e1e1e', letterSpacing: '0.15em' },

  /* Specs pillar — vertical stack on the right */
  specsPillar: {
    display: 'flex', flexDirection: 'column',
    padding: '4px 0 4px 0',
  },
  pillarList: {
    display: 'flex', flexDirection: 'column',
    gap: 1, background: '#0a0a0a',
    border: '1px solid #0a0a0a',
    flex: 1,
  },
  pillarRow: {
    background: '#000', padding: '16px 18px',
    display: 'flex', flexDirection: 'column', gap: 6,
    transition: 'opacity 250ms linear, transform 250ms linear, border-left 250ms linear',
    flex: 1, minHeight: 68,
    justifyContent: 'center',
  },
  pillarKey: {
    fontSize: 9, color: '#444',
    letterSpacing: '0.2em', textTransform: 'uppercase',
  },
  pillarVal: {
    fontSize: 13, color: '#fff',
    letterSpacing: '0.05em', textTransform: 'uppercase',
    fontFamily: "'Cindie2', sans-serif",
    fontWeight: 400, lineHeight: 1.3,
  },
  pillarValRedacted: {
    color: '#3a3a3a',
    fontFamily: "'Share Tech Mono', monospace",
    fontWeight: 400, letterSpacing: '0.02em',
    fontSize: 12,
  },
  specsRedactedHint: {
    marginTop: 18, padding: '12px 0',
    fontFamily: "'Share Tech Mono', monospace",
    fontSize: 10, color: '#444',
    letterSpacing: '0.22em', textTransform: 'uppercase',
    borderTop: '1px solid #1a1a1a',
    textAlign: 'center',
  },

  /* Access / CTA section — full width bottom */
  accessSection: {
    padding: '48px 48px 64px',
    display: 'flex', flexDirection: 'column',
    alignItems: 'center',
    borderTop: '1px solid #0e0e0e',
  },

  /* Footer */
  footerBar: {
    padding: '32px 48px 40px', marginTop: 48,
    display: 'flex', justifyContent: 'space-between',
    fontSize: 9, color: '#222',
    letterSpacing: '0.2em', textTransform: 'uppercase',
    borderTop: '1px solid #0a0a0a',
  },
};

Object.assign(window, { StudioPage, STUDIO_DATA });
