// Project sections — full-bleed alternating, inline expand

const { useState: useStateP } = React;

const PROJECTS = [
  {
    id: "transitiq",
    idx: "01",
    year: "2026",
    name: "TransitIQ",
    nameItalic: null,
    tag: "Fleet operations · Morocco",
    lede: "An OCR + Gemini pipeline that turns physical trip sheets into clean, queryable fleet data — with disambiguation, real-time tracking, and per-trip revenue reporting.",
    stack: ["Next.js 14", "Python", "Gemini AI", "Supabase", "PostgreSQL"],
    problem: "A Moroccan trucking operator was running fleet logistics on paper. Drivers handed in trip sheets; revenue, mileage and maintenance were reconciled by hand. Errors compounded. Decisions arrived late.",
    work: [
      "OCR ingestion of physical trip documents at scale",
      "Gemini-based extraction of structured fields from messy scans",
      "Disambiguation algorithm — matches drivers, vehicles, routes against the live database",
      "Real-time fleet tracking surface with maintenance scheduling",
      "Driver management with duplicate detection",
      "Per-trip revenue reporting, exportable to accounting"
    ],
    role: "Solo build — architecture, AI pipeline, full-stack, deployment.",
    accentLabel: "01 / fleet ops",
  },
  {
    id: "morokeys",
    idx: "02",
    year: "2024 — Now",
    name: "Morokeys",
    nameItalic: null,
    tag: "Hospitality · multilingual concierge",
    lede: "An Airbnb property management platform with a trilingual AI concierge — Arabic, French, English — handling guest comms, bookings, and finance across multiple properties.",
    stack: ["Next.js 16", "Clerk", "Prisma", "PostgreSQL", "Vercel"],
    problem: "Property managers were juggling guest messages across languages, channels and time zones. Bookings, payouts and turnovers lived in separate spreadsheets. The concierge layer was a bottleneck.",
    work: [
      "Multi-tenant dashboard for managers handling multiple properties",
      "AI concierge in Arabic dialect, French, English — context-aware per property",
      "Automated guest communication with human-in-the-loop escalation",
      "Booking sync across distribution channels",
      "Financial reporting — payouts, fees, occupancy, per-property P&L",
      "Auth + roles via Clerk; data layer via Prisma + PostgreSQL"
    ],
    role: "Founding engineer — design, build, ongoing operation.",
    accentLabel: "02 / hospitality saas",
  },
  {
    id: "voice-concierge",
    idx: "03",
    year: "Demo",
    name: "Voice Concierge",
    nameItalic: null,
    tag: "Hospitality voice agent",
    lede: "A multilingual voice agent for riads, hotels, and Airbnb operators — Arabic dialect, French, English. Whisper STT → LLM orchestration → ElevenLabs TTS.",
    stack: ["Whisper", "LLM orchestration", "ElevenLabs", "Telephony"],
    problem: "Small hospitality operators in Morocco lose bookings overnight and during checkout rush. They cannot staff a 24/7 multilingual front desk, but most off-the-shelf voice agents fail on Moroccan dialect.",
    work: [
      "Whisper-based STT tuned for Moroccan dialect, French, and English",
      "LLM orchestration layer: intent handling, tool use, fallback logic",
      "ElevenLabs TTS with voice consistency across languages",
      "Telephony integration — agent answers real phone calls",
      "Handles guest queries, check-in info, local recommendations",
      "Designed as a deployable template for riads and Airbnb operators"
    ],
    role: "Solo build — pipeline architecture and agent design.",
    accentLabel: "03 / voice ops",
  },
];

function ProjectVisual({ id }) {
  // Distinct schematic placeholder per project — abstract, not iconographic
  const accent = "oklch(0.82 0.060 200)";
  const dim = "oklch(0.55 0.010 240)";
  const line = "oklch(0.30 0.010 240)";

  if (id === "transitiq") {
    // Document → fields → table
    return (
      <svg viewBox="0 0 800 450" width="100%" height="100%">
        <defs>
          <pattern id="grid-tx" width="20" height="20" patternUnits="userSpaceOnUse">
            <path d="M 20 0 L 0 0 0 20" fill="none" stroke={line} strokeWidth="0.5" opacity="0.5"/>
          </pattern>
        </defs>
        <rect width="800" height="450" fill="url(#grid-tx)" />
        {/* paper doc */}
        <g transform="translate(60, 70)">
          <rect width="180" height="240" fill="oklch(0.20 0.008 240)" stroke={line}/>
          {[20,40,60,80,110,130,170,190].map((y,i) => (
            <rect key={i} x="16" y={y} width={120 - (i*7)%80} height="4" fill={dim} opacity="0.5"/>
          ))}
          <text x="16" y="225" fill={dim} fontFamily="JetBrains Mono" fontSize="8" letterSpacing="1">TRIP SHEET · 04/26</text>
        </g>
        {/* arrow */}
        <g stroke={accent} strokeWidth="1" fill="none">
          <path d="M 250 190 L 320 190" markerEnd="url(#a-tx)"/>
        </g>
        <defs>
          <marker id="a-tx" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" markerHeight="6" orient="auto">
            <path d="M0,0 L10,5 L0,10 z" fill={accent}/>
          </marker>
        </defs>
        {/* extracted fields */}
        <g transform="translate(340, 90)" fontFamily="JetBrains Mono" fontSize="11">
          {[
            ["driver", "Hassan B."],
            ["truck", "MA-1842-29"],
            ["route", "Casa → Tanger"],
            ["km", "342"],
            ["revenue", "4 200 MAD"],
            ["fuel", "780 MAD"],
          ].map(([k,v], i) => (
            <g key={i} transform={`translate(0, ${i*28})`}>
              <text x="0" y="14" fill={dim}>{k}</text>
              <text x="100" y="14" fill="oklch(0.96 0 0)">{v}</text>
              <rect x="0" y="20" width="280" height="1" fill={line}/>
            </g>
          ))}
        </g>
        {/* live indicator */}
        <g transform="translate(630, 100)">
          <circle cx="0" cy="0" r="4" fill={accent}>
            <animate attributeName="opacity" values="1;0.3;1" dur="1.4s" repeatCount="indefinite"/>
          </circle>
          <text x="14" y="4" fill={dim} fontFamily="JetBrains Mono" fontSize="10" letterSpacing="2">INGEST</text>
        </g>
      </svg>
    );
  }

  if (id === "morokeys") {
    // Multi-property dashboard mock
    return (
      <svg viewBox="0 0 800 450" width="100%" height="100%">
        <rect width="800" height="450" fill="oklch(0.18 0.008 240)"/>
        {/* sidebar */}
        <rect x="0" y="0" width="160" height="450" fill="oklch(0.20 0.008 240)" stroke={line}/>
        <text x="20" y="36" fill="oklch(0.96 0 0)" fontFamily="Inter Tight" fontSize="14" fontWeight="500">Properties</text>
        {["Riad Zitoune", "Marrakech 04", "Essaouira", "Fez Medina", "Casa-Anfa"].map((p,i)=>(
          <g key={i} transform={`translate(20, ${70 + i*32})`}>
            <circle cx="4" cy="6" r="3" fill={i===1 ? accent : dim}/>
            <text x="14" y="10" fill={i===1 ? "oklch(0.96 0 0)" : dim} fontFamily="Inter Tight" fontSize="12">{p}</text>
          </g>
        ))}
        {/* main */}
        <g transform="translate(180, 30)">
          <text fill={dim} fontFamily="JetBrains Mono" fontSize="10" letterSpacing="2">OCCUPANCY · APR 2026</text>
          <text y="32" fill="oklch(0.96 0 0)" fontFamily="Inter Tight" fontSize="32" fontWeight="300">87<tspan fontSize="20" fill={dim}>%</tspan></text>
          {/* bars */}
          <g transform="translate(0, 60)">
            {Array.from({length: 30}, (_, i) => {
              const h = 20 + ((i*37) % 50);
              return <rect key={i} x={i*18} y={80-h} width="10" height={h} fill={i%5===0 ? accent : dim} opacity={i%5===0 ? 0.9 : 0.5}/>
            })}
          </g>
          {/* recent message */}
          <g transform="translate(0, 200)">
            <rect width="560" height="80" fill="oklch(0.20 0.008 240)" stroke={line}/>
            <circle cx="20" cy="20" r="6" fill={accent}/>
            <text x="36" y="24" fill="oklch(0.96 0 0)" fontFamily="Inter Tight" fontSize="12" fontWeight="500">AI concierge → Lina (FR)</text>
            <text x="20" y="52" fill={dim} fontFamily="Inter Tight" fontSize="11">"Bonsoir Lina, votre check-in est confirmé pour 19h. Le code d'entrée…"</text>
            <text x="20" y="68" fill={dim} fontFamily="JetBrains Mono" fontSize="9">auto · 2s ago · escalate? no</text>
          </g>
        </g>
      </svg>
    );
  }

  // voice-concierge — annotated waveform over time
  return (
    <svg viewBox="0 0 800 450" width="100%" height="100%">
      <rect width="800" height="450" fill="oklch(0.18 0.008 240)"/>
      <line x1="0" y1="225" x2="800" y2="225" stroke={line} strokeDasharray="2 4"/>
      {/* incoming wave */}
      <g transform="translate(0, 225)">
        {Array.from({length: 200}, (_, i) => {
          const v = Math.sin(i * 0.18) * Math.sin(i * 0.05) * 70;
          return <line key={i} x1={i*4} y1={-Math.abs(v)} x2={i*4} y2={Math.abs(v)} stroke={dim} strokeWidth="1.5" opacity="0.5"/>
        })}
      </g>
      {/* annotation marks */}
      {[
        {x: 120, label: "ar-MA · greeting"},
        {x: 320, label: "intent: room_service"},
        {x: 540, label: "tool: get_menu()"},
        {x: 700, label: "fr-FR · response"},
      ].map((a, i) => (
        <g key={i} transform={`translate(${a.x}, 80)`}>
          <line x1="0" y1="0" x2="0" y2="120" stroke={accent} strokeWidth="1"/>
          <circle cx="0" cy="0" r="3" fill={accent}/>
          <text x="8" y="-4" fill="oklch(0.96 0 0)" fontFamily="JetBrains Mono" fontSize="10">{a.label}</text>
        </g>
      ))}
      {/* footer */}
      <g transform="translate(40, 410)" fontFamily="JetBrains Mono" fontSize="10" fill={dim} letterSpacing="2">
        <text>00:00</text>
        <text x="180">00:08</text>
        <text x="360">00:16</text>
        <text x="540">00:24</text>
        <text x="720">00:32</text>
      </g>
    </svg>
  );
}

function ProjectSection({ project, index }) {
  const [open, setOpen] = useStateP(false);
  return (
    <section className="bleed project-section" id={project.id}>
      <div className="container">
        <div className="p-meta reveal">
          <span className="idx">// {project.accentLabel}</span>
          <span></span>
          <span className="yr">{project.year}</span>
        </div>
        <h2 className="reveal delay-1">
          {project.name}
        </h2>
        <p className="lede reveal delay-2">{project.lede}</p>
        <div className="stack reveal delay-2">
          {project.stack.map(s => <span key={s}>{s}</span>)}
        </div>
        <button
          className={`expand-btn reveal delay-3 ${open ? "open" : ""}`}
          onClick={() => setOpen(o => !o)}
          aria-expanded={open}
        >
          <span>{open ? "Close case" : "Open case"}</span>
          <span className="icn"></span>
        </button>

        <div className={`project-detail ${open ? "open" : ""}`}>
          <div>
            <h4>The problem</h4>
            <p>{project.problem}</p>
            <h4 style={{ marginTop: 28 }}>Role</h4>
            <p>{project.role}</p>
          </div>
          <div>
            <h4>What I built</h4>
            <ul>
              {project.work.map((w, i) => <li key={i}>{w}</li>)}
            </ul>
          </div>
        </div>

        <div className="p-visual reveal delay-2">
          <ProjectVisual id={project.id} />
        </div>
      </div>
    </section>
  );
}

function Projects() {
  return (
    <>
      {PROJECTS.map((p, i) => <ProjectSection key={p.id} project={p} index={i} />)}
    </>
  );
}

window.Projects = Projects;
