const PROJECTS = [
  {
    name: 'NovaMart', category: 'Web', tag: 'E-Commerce Platform',
    grad: 'linear-gradient(135deg, #0D1B4B 0%, #6C3AFF 100%)',
    pattern: 'rings',
    client: 'NovaMart Global', year: '2025',
    challenge: 'Stitching 12 regional storefronts onto one performant headless platform without losing local merchandising.',
    solution: 'Custom Next.js + Sanity headless stack with edge-cached catalogs and a unified checkout. Migrated 400k SKUs over two sprints.',
    stack: ['Next.js', 'Sanity', 'Stripe', 'Vercel Edge', 'Algolia'],
    outcome: '+38% conversion · 2.1s TTI · $4.2M added GMV in Q1',
  },
  {
    name: 'PulseTrack', category: 'Apps', tag: 'Health Monitoring App',
    grad: 'linear-gradient(135deg, #03040A 0%, #00C8E0 100%)',
    pattern: 'wave',
    client: 'PulseTrack Health', year: '2025',
    challenge: 'Real-time vitals on a cross-platform app that doctors actually want to use — and FDA-grade audit trails.',
    solution: 'React Native shell with a Rust-powered sync engine, biometric sign-in, and a clinician web companion.',
    stack: ['React Native', 'Rust', 'Postgres', 'WebSockets', 'AWS'],
    outcome: '92% 30-day retention · Featured on App Store Health',
  },
  {
    name: 'QuantumBrand', category: 'Branding', tag: 'Visual Identity System',
    grad: 'linear-gradient(135deg, #1B0A2E 0%, #6C3AFF 100%)',
    pattern: 'grid',
    client: 'Quantum Labs', year: '2024',
    challenge: 'Repositioning a quantum-computing startup with a brand that felt as advanced as the science.',
    solution: 'Wordmark, motion identity, 80-page guidelines and a Figma component kit for product + marketing.',
    stack: ['Figma', 'Lottie', 'Glyphs', 'Brand strategy'],
    outcome: '3x inbound press · Series B closed in 6 months',
  },
  {
    name: 'OrbitalSocial', category: 'Social Media', tag: 'Always-On Content Studio',
    grad: 'linear-gradient(135deg, #0A1A0A 0%, #00C8E0 100%)',
    pattern: 'dots',
    client: 'Orbital Coffee', year: '2025',
    challenge: 'A coffee chain with strong product but a flat, inconsistent feed across 4 markets.',
    solution: 'Editorial system + weekly shoot rhythm + paid creative testing. 80 posts a month, one tone of voice.',
    stack: ['Figma', 'Meta Ads', 'TikTok', 'Analytics'],
    outcome: '+220% engagement · 6.4x ROAS on paid social',
  },
  {
    name: 'MindFlowAI', category: 'AI & Systems', tag: 'AI Automation Pipeline',
    grad: 'linear-gradient(135deg, #1A0D0D 0%, #6C3AFF 100%)',
    pattern: 'circuit',
    client: 'MindFlow', year: '2025',
    challenge: '600+ manual ops per week across sales, billing and onboarding. Burning out a 12-person team.',
    solution: 'LLM-powered intake, Temporal-orchestrated workflows, and a custom review console for ambiguous cases.',
    stack: ['Python', 'OpenAI', 'Temporal', 'Postgres', 'Next.js'],
    outcome: '78% of ops automated · $0.4M/yr saved · 6h reclaimed/person/week',
  },
  {
    name: 'CoreStack', category: 'AI & Systems', tag: 'Enterprise ERP System',
    grad: 'linear-gradient(135deg, #0D1B4B 0%, #00C8E0 100%)',
    pattern: 'rings',
    client: 'Corestack Manufacturing', year: '2024',
    challenge: 'A 25-year-old ERP held together by spreadsheets and 3am phone calls.',
    solution: 'Phased rewrite to a modular Node + Postgres core with a React admin and live dashboards.',
    stack: ['Node.js', 'Postgres', 'React', 'Redis', 'Docker'],
    outcome: '4x faster order cycle · Single source of truth across 7 plants',
  },
];

const CATEGORIES = ['All', 'Web', 'Apps', 'Branding', 'Social Media', 'AI & Systems'];

function PortfolioPattern({ kind }) {
  if (kind === 'rings') return (
    <svg width="100%" height="100%" viewBox="0 0 400 225" preserveAspectRatio="xMidYMid slice" style={{ position: 'absolute', inset: 0, opacity: 0.4 }}>
      <g fill="none" stroke="white" strokeWidth="0.8">
        <circle cx="320" cy="120" r="40" />
        <circle cx="320" cy="120" r="70" opacity="0.6" />
        <circle cx="320" cy="120" r="100" opacity="0.4" />
        <circle cx="320" cy="120" r="130" opacity="0.2" />
        <circle cx="320" cy="120" r="6" fill="white" />
      </g>
    </svg>
  );
  if (kind === 'wave') return (
    <svg width="100%" height="100%" viewBox="0 0 400 225" preserveAspectRatio="none" style={{ position: 'absolute', inset: 0, opacity: 0.55 }}>
      <g fill="none" stroke="white" strokeWidth="1">
        {[0,1,2,3,4,5,6,7].map(i => (
          <path key={i} d={`M0 ${50 + i * 22} Q 100 ${20 + i * 22} 200 ${50 + i * 22} T 400 ${50 + i * 22}`} opacity={1 - i*0.1} />
        ))}
      </g>
    </svg>
  );
  if (kind === 'grid') return (
    <svg width="100%" height="100%" viewBox="0 0 400 225" preserveAspectRatio="xMidYMid slice" style={{ position: 'absolute', inset: 0, opacity: 0.35 }}>
      <defs>
        <pattern id="pg" width="22" height="22" patternUnits="userSpaceOnUse">
          <path d="M22 0H0V22" fill="none" stroke="white" strokeWidth="0.5" />
        </pattern>
      </defs>
      <rect width="400" height="225" fill="url(#pg)" />
      <polygon points="280,60 340,100 280,140 220,100" fill="none" stroke="white" strokeWidth="1.2" />
      <polygon points="280,75 325,100 280,125 235,100" fill="none" stroke="white" strokeWidth="0.6" />
    </svg>
  );
  if (kind === 'dots') return (
    <svg width="100%" height="100%" viewBox="0 0 400 225" preserveAspectRatio="xMidYMid slice" style={{ position: 'absolute', inset: 0, opacity: 0.5 }}>
      <g fill="white">
        {Array.from({length: 80}).map((_, i) => {
          const x = (i * 47) % 400;
          const y = ((i * 31) % 225);
          const r = (i % 7 === 0 ? 2.5 : 1);
          return <circle key={i} cx={x} cy={y} r={r} opacity={0.5 + (i%5)/10} />;
        })}
      </g>
    </svg>
  );
  // circuit
  return (
    <svg width="100%" height="100%" viewBox="0 0 400 225" preserveAspectRatio="xMidYMid slice" style={{ position: 'absolute', inset: 0, opacity: 0.45 }}>
      <g fill="none" stroke="white" strokeWidth="1">
        <path d="M0 60 L120 60 L120 30 L260 30 L260 110 L340 110 L340 80 L400 80" />
        <path d="M0 180 L80 180 L80 150 L200 150 L200 200 L320 200" />
        <path d="M0 110 L60 110 L60 90 L160 90 L160 60" />
        <circle cx="120" cy="60" r="3" fill="white" />
        <circle cx="260" cy="110" r="3" fill="white" />
        <circle cx="200" cy="150" r="3" fill="white" />
        <circle cx="340" cy="80" r="3" fill="white" />
        <circle cx="60" cy="90" r="3" fill="white" />
      </g>
    </svg>
  );
}

function PortfolioModal({ project, onClose }) {
  React.useEffect(() => {
    if (!project) return;
    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 = '';
    };
  }, [project, onClose]);

  if (!project) return null;

  return (
    <div className="modal-back" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <button className="modal-close" onClick={onClose} aria-label="Close"><IconClose size={18} /></button>
        <div className="modal-hero" style={{ background: project.grad }}>
          <PortfolioPattern kind={project.pattern} />
          <div className="modal-hero-meta">
            <span className="modal-tag">{project.category}</span>
            <span>{project.year}</span>
          </div>
          <div className="modal-hero-title">
            <h3>{project.name}</h3>
            <p>{project.tag}</p>
          </div>
        </div>
        <div className="modal-body">
          <div className="modal-row">
            <div className="modal-label">CLIENT</div>
            <div className="modal-val">{project.client}</div>
          </div>
          <div className="modal-section">
            <div className="modal-label">CHALLENGE</div>
            <p>{project.challenge}</p>
          </div>
          <div className="modal-section">
            <div className="modal-label">SOLUTION</div>
            <p>{project.solution}</p>
          </div>
          <div className="modal-section">
            <div className="modal-label">TECH STACK</div>
            <div className="modal-chips">
              {project.stack.map((t, i) => <span key={i} className="modal-chip">{t}</span>)}
            </div>
          </div>
          <div className="modal-outcome">
            <div className="modal-label">OUTCOME</div>
            <p>{project.outcome}</p>
          </div>
        </div>
      </div>
      <style>{`
        .modal-back {
          position: fixed; inset: 0; z-index: 10001;
          background: rgba(3,4,10,0.85);
          backdrop-filter: blur(16px);
          -webkit-backdrop-filter: blur(16px);
          display: flex; align-items: center; justify-content: center;
          padding: 24px;
          animation: fade-in 0.25s ease;
        }
        @keyframes fade-in { from { opacity: 0; } to { opacity: 1; } }
        .modal {
          width: 100%; max-width: 680px;
          max-height: 90vh; overflow-y: auto;
          background: var(--nebula-deep);
          border: 1px solid rgba(0,200,224,0.25);
          border-radius: 20px;
          box-shadow: 0 30px 80px rgba(0,0,0,0.6), 0 0 60px rgba(0,200,224,0.15);
          position: relative;
          animation: modal-in 0.35s cubic-bezier(0.2,0.7,0.2,1);
        }
        @keyframes modal-in {
          from { opacity: 0; transform: scale(0.96) translateY(20px); }
          to { opacity: 1; transform: scale(1) translateY(0); }
        }
        .modal-close {
          position: absolute; top: 16px; right: 16px;
          width: 36px; height: 36px;
          background: rgba(3,4,10,0.6);
          border: 1px solid rgba(0,200,224,0.2);
          border-radius: 50%;
          display: flex; align-items: center; justify-content: center;
          color: var(--stardust-white);
          z-index: 2;
          transition: background 0.2s, transform 0.2s;
        }
        .modal-close:hover { background: var(--stellar-cyan); color: var(--space-void); transform: rotate(90deg); }
        .modal-hero {
          position: relative;
          aspect-ratio: 16/9;
          overflow: hidden;
        }
        .modal-hero-meta {
          position: absolute; top: 18px; left: 22px;
          display: flex; gap: 10px;
          font-family: 'Space Mono', monospace;
          font-size: 11px; letter-spacing: 0.16em;
          color: rgba(255,255,255,0.7);
        }
        .modal-tag {
          background: rgba(0,0,0,0.35);
          border: 1px solid rgba(255,255,255,0.25);
          border-radius: 4px;
          padding: 3px 9px;
          color: white;
        }
        .modal-hero-title {
          position: absolute; left: 22px; right: 22px; bottom: 20px;
          color: white;
        }
        .modal-hero-title h3 {
          font-family: 'Orbitron', sans-serif;
          font-size: 32px; font-weight: 700;
          margin-bottom: 4px;
          letter-spacing: 0.02em;
        }
        .modal-hero-title p {
          font-family: 'Syne', sans-serif;
          font-size: 14px;
          color: rgba(255,255,255,0.75);
        }
        .modal-body { padding: 28px 32px 32px; }
        .modal-row { display: flex; justify-content: space-between; align-items: center; padding-bottom: 18px; border-bottom: 1px solid rgba(0,200,224,0.1); margin-bottom: 22px; }
        .modal-section { margin-bottom: 22px; }
        .modal-outcome {
          padding: 20px;
          margin-top: 24px;
          background: linear-gradient(135deg, rgba(0,200,224,0.08), rgba(108,58,255,0.08));
          border: 1px solid rgba(0,200,224,0.25);
          border-radius: 12px;
        }
        .modal-label {
          font-family: 'Space Mono', monospace;
          font-size: 11px; letter-spacing: 0.24em;
          color: var(--stellar-cyan);
          margin-bottom: 8px;
        }
        .modal-val { font-family: 'Syne'; font-size: 16px; color: var(--stardust-white); font-weight: 600; }
        .modal-section p, .modal-outcome p {
          font-family: 'Syne', sans-serif;
          font-size: 15px; line-height: 1.7;
          color: rgba(232,238,255,0.78);
        }
        .modal-chips { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 6px; }
        .modal-chip {
          font-family: 'Space Mono', monospace;
          font-size: 11px;
          padding: 6px 12px;
          background: rgba(0,200,224,0.08);
          border: 1px solid rgba(0,200,224,0.22);
          border-radius: 4px;
          color: var(--stardust-white);
        }
      `}</style>
    </div>
  );
}

function Portfolio() {
  const [filter, setFilter] = React.useState('All');
  const [open, setOpen] = React.useState(null);

  const filtered = filter === 'All' ? PROJECTS : PROJECTS.filter(p => p.category === filter);

  return (
    <section id="portfolio" data-screen-label="04 Portfolio" style={{
      padding: 'clamp(80px, 10vw, 140px) 0',
      background: 'var(--space-void)',
    }}>
      <div className="container">
        <div className="section-head reveal">
          <span className="eyebrow">≫ CASE STUDIES</span>
          <h2>Our Work</h2>
          <p>Projects we're proud of. Results clients love.</p>
        </div>

        <div className="filter-row reveal" data-delay="1">
          {CATEGORIES.map(c => (
            <button
              key={c}
              className={`filter-pill ${filter === c ? 'active' : ''}`}
              onClick={() => setFilter(c)}
            >
              {c}
            </button>
          ))}
          <div className="filter-count">
            <span style={{ color: 'var(--stellar-cyan)' }}>{filtered.length}</span> / {PROJECTS.length} projects
          </div>
        </div>

        <div className="portfolio-grid">
          {filtered.map((p, i) => (
            <article key={p.name} className="port-card reveal" data-delay={i % 3 + 1} onClick={() => setOpen(p)}>
              <div className="port-thumb" style={{ background: p.grad }}>
                <PortfolioPattern kind={p.pattern} />
                <div className="port-thumb-meta">
                  <span className="port-tag">{p.category}</span>
                  <span className="port-year">{p.year}</span>
                </div>
                <div className="port-hover-cta">
                  <span>View case study</span>
                  <IconArrowRight size={14} />
                </div>
              </div>
              <div className="port-info">
                <div>
                  <div className="port-name">{p.name}</div>
                  <div className="port-sub">{p.tag}</div>
                </div>
                <div className="port-arrow"><IconArrowRight size={18} /></div>
              </div>
            </article>
          ))}
        </div>

        <div className="reveal" style={{ marginTop: 80, textAlign: 'center' }}>
          <p style={{ fontFamily: 'Syne', fontSize: 20, color: 'var(--stardust-white)', marginBottom: 22, fontWeight: 500 }}>
            Want results like these?
          </p>
          <a href="#contact" className="btn-primary" onClick={(e)=>{e.preventDefault(); document.getElementById('contact').scrollIntoView({behavior:'smooth'});}}>
            <IconArrowRight size={18} /> Start Your Project
          </a>
        </div>
      </div>

      <PortfolioModal project={open} onClose={() => setOpen(null)} />

      <style>{`
        .filter-row {
          display: flex; flex-wrap: wrap; gap: 8px;
          margin-bottom: 40px;
          align-items: center;
        }
        .filter-pill {
          font-family: 'Space Mono', monospace;
          font-size: 12px; letter-spacing: 0.1em;
          padding: 10px 18px;
          background: rgba(0,200,224,0.06);
          border: 1px solid rgba(0,200,224,0.15);
          border-radius: 6px;
          color: var(--asteroid-grey);
          cursor: pointer;
          transition: all 0.25s;
        }
        .filter-pill:hover { color: var(--stardust-white); border-color: rgba(0,200,224,0.3); }
        .filter-pill.active {
          background: rgba(0,200,224,0.15);
          border-color: var(--stellar-cyan);
          color: var(--stellar-cyan);
          box-shadow: 0 0 16px rgba(0,200,224,0.2);
        }
        .filter-count {
          margin-left: auto;
          font-family: 'Space Mono', monospace;
          font-size: 12px; letter-spacing: 0.1em;
          color: var(--asteroid-grey);
        }
        @media (max-width: 600px) { .filter-count { display: none; } }

        .portfolio-grid {
          display: grid;
          grid-template-columns: repeat(3, 1fr);
          gap: 20px;
        }
        @media (max-width: 980px) { .portfolio-grid { grid-template-columns: repeat(2, 1fr); } }
        @media (max-width: 600px) { .portfolio-grid { grid-template-columns: 1fr; } }

        .port-card {
          border-radius: 16px;
          overflow: hidden;
          border: 1px solid rgba(0,200,224,0.12);
          background: var(--nebula-deep);
          cursor: pointer;
          transition: transform 0.3s, border-color 0.3s, box-shadow 0.3s;
        }
        .port-card:hover {
          transform: translateY(-6px) scale(1.005);
          border-color: rgba(0,200,224,0.45);
          box-shadow: 0 24px 60px rgba(0,200,224,0.12);
        }
        .port-thumb {
          position: relative;
          aspect-ratio: 16/9;
          overflow: hidden;
        }
        .port-thumb-meta {
          position: absolute; top: 14px; left: 14px; right: 14px;
          display: flex; justify-content: space-between; align-items: center;
          z-index: 2;
          font-family: 'Space Mono', monospace;
          font-size: 10px; letter-spacing: 0.18em;
          color: rgba(255,255,255,0.75);
        }
        .port-tag {
          padding: 4px 10px;
          background: rgba(0,0,0,0.35);
          border: 1px solid rgba(255,255,255,0.25);
          border-radius: 4px;
          color: white;
        }
        .port-year {
          background: rgba(0,0,0,0.35);
          padding: 4px 8px;
          border-radius: 4px;
        }
        .port-hover-cta {
          position: absolute; left: 14px; right: 14px; bottom: 14px;
          display: flex; gap: 8px; align-items: center;
          padding: 10px 14px;
          background: rgba(3,4,10,0.7);
          border: 1px solid rgba(0,200,224,0.4);
          backdrop-filter: blur(6px);
          border-radius: 8px;
          color: var(--stellar-cyan);
          font-family: 'Syne', sans-serif;
          font-size: 12.5px; font-weight: 600;
          letter-spacing: 0.05em;
          opacity: 0;
          transform: translateY(8px);
          transition: opacity 0.3s, transform 0.3s;
        }
        .port-card:hover .port-hover-cta { opacity: 1; transform: translateY(0); }
        .port-info {
          display: flex; justify-content: space-between; align-items: center;
          padding: 20px 22px;
          background: rgba(10,14,26,0.98);
          border-top: 1px solid rgba(0,200,224,0.08);
        }
        .port-name {
          font-family: 'Syne', sans-serif;
          font-size: 17px; font-weight: 700;
          color: var(--stardust-white);
          margin-bottom: 2px;
        }
        .port-sub {
          font-family: 'Syne', sans-serif;
          font-size: 13px;
          color: var(--asteroid-grey);
        }
        .port-arrow {
          color: var(--asteroid-grey);
          transition: transform 0.25s, color 0.25s;
        }
        .port-card:hover .port-arrow { color: var(--stellar-cyan); transform: translateX(4px); }
      `}</style>
    </section>
  );
}

window.Portfolio = Portfolio;
