/* global React, Button, BracketLabel, MonoMeta, GenerativeArt, Reveal, SectionHead, Counter */
const { useEffect: useEffectCS } = React;

const CASE_STUDIES = {
  "case-01": {
    id: "01", num: "01 / 03",
    title: "Droplet",
    italic: "Droplet",
    sub: "UX · Product · Brand",
    year: "2025",
    role: "End-to-end UX & UI",
    client: "Self-directed",
    duration: "Studio semester",
    art: "droplet",
    fullStudyUrl: "case-droplet/",
    summary: "A hydration app rethought for neurodivergent users: students, remote workers, anyone whose days don't fit a 9-to-5 mold. Calm surfaces, one-tap logging, and a pause-without-guilt model in place of streaks and shame.",
    challenge: "Standard water apps quietly fail neurodivergent users. Habit-trackers assume a stable routine, perfect attention, and a tolerance for friction. ADHD and autistic users meet multi-step logging, generic interval reminders, and red \"missed goal\" rings that turn an inconsistent week into a story of personal failure. The pattern is consistent: download, configure, miss two days, abandon.",
    solution: "A dark, low-stimulation interface that reads as a moment of breath rather than a productivity tool. Progress is communicated through luminance and color temperature: warm glow, not red ring. Logging happens in one tap from any surface: widget, lock screen, watch, Dynamic Island. The full app is for review, not for the daily action.",
    process: [
      { num: "01", title: "Listen", desc: "Semi-structured interviews with neurodivergent adults who had abandoned at least one habit-tracker, paired with a journey audit of three top-rated water apps. Synthesis through affinity mapping into two personas and a five-stage failure journey." },
      { num: "02", title: "System", desc: "A calm design system grounded in a dark surface, soft signal colors, and reusable patterns for state without shame. Tokens, components, and a pulse-ring motion language replace the punitive red rings of the category." },
      { num: "03", title: "Build", desc: "High-fidelity iOS prototype across phone, home screen widget, Lock Screen complication, and Apple Watch face. Every entry point logs the most-used preset in a single touch." },
    ],
    results: [
      { num: "2", unit: "", desc: "Composite personas anchored every decision." },
      { num: "5", unit: "", desc: "Failure stages mapped in the abandonment journey." },
      { num: "1", unit: "", desc: "Tap to log from widget, lock screen, or watch." },
      { num: "4", unit: "", desc: "Surfaces designed end-to-end for ambient use." },
    ],
    quote: "A water app that doesn't punish you for being human.",
    quoteAttr: "Droplet · design thesis",
  },
  "case-02": {
    id: "02", num: "02 / 03",
    title: "Forage",
    italic: "Forage",
    sub: "UX · iOS Native · Local Discovery",
    year: "2026",
    role: "End-to-end UX & UI",
    client: "Self-directed",
    duration: "Studio semester",
    art: "lines",
    fullStudyUrl: "case-forage/",
    summary: "An event discovery app for mid-size cities, where the local scene is real but nearly impossible to find. Forage surfaces underground events through a network of local scouts instead of an algorithm, with a Tonight Mode for same-day plans and private circles for sharing with a few trusted friends.",
    challenge: "People in mid-size cities feel like nothing is happening. It's rarely true. Eventbrite and Facebook Events are built for big, ticketed, heavily promoted events, and the open mics, pop-up markets, and gallery nights fall through the cracks. So Maya hears about the great open mic on Monday, from a coworker, two days too late.",
    solution: "A dark, editorial iOS app where you browse by vibe (Chill, Loud, Raw, Odd) instead of category. Every event carries the name of the scout who posted it, someone with a reputation to protect. Tonight Mode shifts the whole interface into urgency: pink accent, sorted by distance, share button up front. The result reads more like a city zine than a startup dashboard.",
    process: [
      { num: "01", title: "Listen", desc: "Interviews with recent transplants and longtime locals, alongside a journey audit of four mainstream platforms. The findings became two personas and a five-stage pattern of how a night out quietly fails to happen: search, deflate, noise, dead end, stay home." },
      { num: "02", title: "System", desc: "A dark design system built on acid green, pulse pink, and Barlow Condensed. Editorial and urban rather than corporate. The vibe pills, scout badges, and Tonight Mode tags came together as a component library before any screen got designed." },
      { num: "03", title: "Build", desc: "A high-fidelity iOS prototype across four flows: vibe-filtered discovery, Tonight Mode, scout submission, and circle sharing. Every interaction kept coming back to the same question, which is whether it adds friction to something that should take seconds." },
    ],
    results: [
      { num: "2", unit: "", desc: "Personas that anchored every design decision." },
      { num: "5", unit: "", desc: "Stages mapped in the way a night out falls apart." },
      { num: "4", unit: "", desc: "Vibes doing the work of twenty categories." },
      { num: "10", unit: "", desc: "Max circle size, and the cap is the point." },
    ],
    quote: "The discovery layer for local culture is broken. That's the gap I wanted to design into.",
    quoteAttr: "Forage · design notes",
  },
  "case-03": {
    id: "03", num: "03 / 03",
    title: "Ember & Oak",
    italic: "& Oak",
    sub: "Identity · Freelance",
    year: "2024",
    role: "Brand design",
    client: "Local roaster, Fort Worth",
    duration: "Three months",
    art: "rings",
    summary: "Brand identity for a small Fort Worth coffee roaster, a friend's business in its second year. My first real freelance brief where someone trusted me with something they actually cared about.",
    challenge: "A roaster with genuine craft and a logo that didn't reflect any of it. No big agency process, no launch campaign. They just needed something considered that could live on a kraft bag, a sticker, and a simple site without looking like a template.",
    solution: "A monogram drawn from the geometry of a roasting drum. A warm amber as the only color in an otherwise quiet, near-monochrome system. Simple enough to work small, deliberate enough to feel like it belongs to them.",
    process: [
      { num: "01", title: "Listen", desc: "Spent a morning at the roastery before sketching anything. The brief was loose, so I asked a lot of questions: what they were proud of, what embarrassed them about the old mark, what they wanted people to feel. That conversation shaped everything." },
      { num: "02", title: "Sketch", desc: "A lot of monogram concepts. Went back and forth between wordmark-first and symbol-first. The drum geometry showed up in round three and stuck. It came from a photo of their actual machine, not a shape I made up." },
      { num: "03", title: "Deliver", desc: "Final files, a simple one-page brand sheet, and a walkthrough conversation. First time handing something off to someone who would actually live with it. That felt different than any school brief." },
    ],
    results: [
      { num: "3", unit: "", desc: "Rounds of concepts before we both felt it was right." },
      { num: "1", unit: "", desc: "Mark. Still on the bag, unchanged." },
      { num: "0", unit: "", desc: "Revisions requested after final delivery." },
      { num: "1", unit: "", desc: "First freelance project I'm genuinely proud of." },
    ],
    quote: "It doesn't look like it was designed. That's the best thing anyone's said to me about my work so far.",
    quoteAttr: "Jaeden Thai · reflection",
  },
};

window.CASE_STUDIES = CASE_STUDIES;

function CaseStudyPage({ slug, navigate }) {
  const cs = CASE_STUDIES[slug];
  const allSlugs = Object.keys(CASE_STUDIES);
  useEffectCS(() => { window.scrollTo(0, 0); }, [slug]);
  if (!cs) return null;

  const nextSlug = allSlugs[(allSlugs.indexOf(slug) + 1) % allSlugs.length];
  const next = CASE_STUDIES[nextSlug];
  const firstWord = cs.title.replace(cs.italic, "").trim();
  const nextFirst = next.title.replace(next.italic, "").trim();

  return (
    <div className="cs-page page-enter" data-screen-label={"Case Study " + cs.id}>
      <div className="cs-back-bar">
        <a onClick={() => navigate("home")}>← Back to the index</a>
        <span>{cs.num}</span>
      </div>

      <div className="cs-thumbs">
        {allSlugs.map(s => {
          const c = CASE_STUDIES[s];
          return (
            <a key={s} className={"cs-thumb" + (s === slug ? " active" : "")} onClick={() => navigate(s)}>
              <div style={{ position: "absolute", inset: 0 }}><GenerativeArt seed={parseInt(c.id) * 17 + 5} variant={c.art} /></div>
              <span className="bracket-label label" style={{ color: "var(--fg-3)" }}>{c.title}</span>
            </a>
          );
        })}
      </div>

      <div className="cs-meta-row">
        <div className="cs-meta-cell">
          <span className="label">Year</span>
          <span className="value">{cs.year}</span>
        </div>
        <div className="cs-meta-cell">
          <span className="label">Role</span>
          <span className="value">{cs.role}</span>
        </div>
        <div className="cs-meta-cell">
          <span className="label">Duration</span>
          <span className="value">{cs.duration}</span>
        </div>
        <div className="cs-title-block">
          <h1 className="cs-title">{firstWord}<em>{firstWord ? " " : ""}{cs.italic}</em></h1>
        </div>
      </div>

      <div className="cs-hero">
        <div className="cs-hero-img">
          <div style={{ position: "absolute", inset: 0 }}><GenerativeArt seed={parseInt(cs.id) * 31} variant={cs.art} /></div>
          <span className="bracket-label label" style={{ color: "var(--fg-3)" }}>Frame · {cs.title}</span>
        </div>
      </div>

      <section className="cs-overview">
        <Reveal>
          <h4>The challenge</h4>
          <p>{cs.challenge}</p>
        </Reveal>
        <Reveal delay={120}>
          <h4>The response</h4>
          <p>{cs.solution}</p>
        </Reveal>
      </section>

      {cs.fullStudyUrl && (
        <section className="cs-full-study" style={{
          maxWidth: 1200, margin: "0 auto", padding: "0 clamp(20px, 5vw, 64px) 96px",
        }}>
          <a href={cs.fullStudyUrl} target="_blank" rel="noopener" className="cs-full-study-link" style={{
            display: "flex", alignItems: "center", justifyContent: "space-between",
            flexWrap: "wrap", gap: "20px 32px",
            padding: "clamp(24px, 4vw, 36px)",
            border: "1px solid var(--line-1)", borderRadius: 2,
            background: "var(--surface-low)",
            textDecoration: "none", color: "inherit",
            transition: "border-color 240ms ease",
          }}
          onMouseEnter={(e) => { e.currentTarget.style.borderColor = "var(--fg-2)"; }}
          onMouseLeave={(e) => { e.currentTarget.style.borderColor = "var(--line-1)"; }}>
            <div style={{ display: "flex", flexDirection: "column", gap: 10, flex: "1 1 320px", minWidth: 0 }}>
              <BracketLabel>The full case study</BracketLabel>
              <h3 style={{
                fontFamily: "var(--font-serif)", fontStyle: "italic",
                fontSize: "clamp(26px, 3.4vw, 40px)", fontWeight: 400, lineHeight: 1.1,
                color: "var(--fg-1)", margin: 0,
              }}>Open the long-form study →</h3>
              <span style={{ color: "var(--fg-3)", fontSize: 14, lineHeight: 1.5, marginTop: 2 }}>
                Research, journey maps, the design system, wireframes, and the interactive iOS prototype.
              </span>
            </div>
            <span style={{
              fontFamily: "var(--font-mono, monospace)", fontSize: 11, letterSpacing: 1.2,
              color: "var(--fg-3)", textTransform: "uppercase",
              flex: "0 1 auto", wordBreak: "break-all",
            }}>jaedenthai.com / {cs.fullStudyUrl.replace(/\/$/, "")}</span>
          </a>
        </section>
      )}

      <section className="cs-process-section">
        <div className="cs-process-head">
          <BracketLabel>The work</BracketLabel>
        </div>
        <div className="cs-process-grid">
          {cs.process.map((p, i) => (
            <div key={i} className="cs-process-cell">
              <div className="cs-process-text">
                <span className="num">— 0{i + 1}</span>
                <h4>{p.title}</h4>
                <p>{p.desc}</p>
              </div>
              <div className="cs-process-img">
                <div style={{ position: "absolute", inset: 0 }}>
                  <GenerativeArt seed={parseInt(cs.id) * 57 + i * 11} variant={i % 2 === 0 ? "grid" : "lines"} />
                </div>
              </div>
            </div>
          ))}
        </div>
      </section>

      <section className="cs-results">
        <div className="section-head" style={{ padding: 0 }}>
          <h2 className="section-title">What <em>came of it</em></h2>
          <span className="mono-meta">Post-launch</span>
        </div>
        <div className="cs-results-grid">
          {cs.results.map((r, i) => (
            <div key={i} className="cs-result">
              <div className="num">
                <Counter to={parseFloat(r.num)} suffix={r.unit} />
              </div>
              <div className="desc">{r.desc}</div>
            </div>
          ))}
        </div>
      </section>

      <section className="cs-quote">
        <BracketLabel style={{ marginBottom: 32, display: "inline-flex" }}>In their words</BracketLabel>
        <q>{cs.quote}</q>
        <span className="cs-quote-attr">— {cs.quoteAttr}</span>
      </section>

      <section className="cs-final">
        <div className="section-head" style={{ padding: 0 }}>
          <h2 className="section-title">A few <em>final frames</em></h2>
          <span className="mono-meta">Three</span>
        </div>
        <div className="cs-final-grid">
          {[0, 1, 2].map(i => (
            <div key={i} className="cs-final-cell">
              <div style={{ position: "absolute", inset: 0 }}>
                <GenerativeArt seed={parseInt(cs.id) * 91 + i * 7} variant={["blocks", "rings", "lines"][i]} />
              </div>
              <div className="grain-overlay" style={{ position: "absolute", inset: 0, backgroundImage: "url(../assets/grain.svg)", backgroundSize: "240px", opacity: 0.12, mixBlendMode: "screen" }} />
              <span className="bracket-label label" style={{ color: "var(--fg-3)" }}>Frame 0{i + 1}</span>
            </div>
          ))}
        </div>
      </section>

      <a className="cs-next" onClick={() => navigate(nextSlug)}>
        <div className="label-stack">
          <BracketLabel>Next · {next.num}</BracketLabel>
          <h2>{nextFirst}<em>{nextFirst ? " " : ""}{next.italic}</em></h2>
        </div>
        <span className="cs-next-arrow">→</span>
      </a>
    </div>
  );
}

window.CaseStudyPage = CaseStudyPage;
