// =========================================================================
// Page sections — Hero, About, Work, Projects, Contact
// + helpers: SectionHeader, ProjectCard, StackMarquee, MetaRow
// =========================================================================
const { useState: useSecState, useEffect: useSecEffect, useRef: useSecRef } = React;

// ---------- helpers --------------------------------------------------------

function SectionHeader({ number, eyebrow, title, kicker }) {
  const isMobile = window.useIsMobile();
  return (
    <div style={{
      display: "grid",
      gridTemplateColumns: isMobile ? "1fr" : "120px 1fr",
      gap: isMobile ? 16 : "clamp(20px, 4vw, 56px)",
      alignItems: "start",
      marginBottom: isMobile ? 40 : 64,
    }}>
      {!isMobile && (
        <div>
          <div style={{
            fontFamily: "var(--font-mono)",
            fontSize: 14,
            letterSpacing: "0.08em",
            color: "var(--fg-faint)",
            paddingTop: 14,
          }}>{number}</div>
          <span style={{
            display: "block",
            width: 36, height: 1,
            background: "var(--accent)",
            marginTop: 12,
          }} />
        </div>
      )}
      <div>
        {isMobile && (
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--fg-faint)", letterSpacing: "0.08em", marginBottom: 12 }}>
            {number} <span style={{ display: "inline-block", width: 24, height: 1, background: "var(--accent)", verticalAlign: "middle", marginLeft: 8 }} />
          </div>
        )}
        <Reveal>
          <div className="eyebrow" style={{ marginBottom: 16 }}>{eyebrow}</div>
        </Reveal>
        <TextReveal as="h2"
          lines={String(title).split("\n")}
          style={{
            fontFamily: "var(--font-display)",
            fontWeight: 600,
            fontSize: isMobile ? "clamp(32px, 10vw, 52px)" : "clamp(40px, 5vw, 84px)",
            lineHeight: 1.05,
            letterSpacing: "-0.025em",
            textWrap: "balance",
            margin: 0,
            color: "var(--fg)",
          }} />
        {kicker && (
          <Reveal delay={300}>
            <p style={{
              marginTop: 24,
              maxWidth: 680,
              fontSize: isMobile ? 16 : 18,
              lineHeight: 1.6,
              color: "var(--fg-muted)",
            }}>{kicker}</p>
          </Reveal>
        )}
      </div>
    </div>
  );
}

function MetaRow({ items }) {
  return (
    <div style={{
      display: "flex",
      gap: 28,
      flexWrap: "wrap",
      fontFamily: "var(--font-mono)",
      fontSize: 12,
      letterSpacing: "0.08em",
      color: "var(--fg-muted)",
      textTransform: "uppercase",
    }}>
      {items.map(([k, v], i) => (
        <span key={i} style={{ display: "inline-flex", alignItems: "center", gap: 8 }}>
          <span style={{ color: "var(--fg-faint)" }}>{k}</span>
          <span style={{ width: 16, height: 1, background: "var(--border-loud)", display: "inline-block" }} />
          <span style={{ color: "var(--fg)" }}>{v}</span>
        </span>
      ))}
    </div>
  );
}

// ---------- Terminal Window -----------------------------------------------

function useIsWide() {
  const [wide, setWide] = useSecState(() => window.innerWidth > 960);
  useSecEffect(() => {
    const fn = () => setWide(window.innerWidth > 960);
    window.addEventListener("resize", fn, { passive: true });
    return () => window.removeEventListener("resize", fn);
  }, []);
  return wide;
}

function StaggerLine({ delay, children }) {
  const [vis, setVis] = useSecState(false);
  useSecEffect(() => {
    const t = setTimeout(() => setVis(true), delay);
    return () => clearTimeout(t);
  }, []);
  return (
    <div style={{
      opacity: vis ? 1 : 0,
      transform: vis ? "none" : "translateY(3px)",
      transition: "opacity 160ms ease, transform 160ms ease",
      lineHeight: 1.7,
    }}>{children}</div>
  );
}

function TerminalWindow() {
  const { lang } = React.useContext(window.LangContext);
  const [ref, inView] = useInView({ threshold: 0.15 });
  const [step, setStep] = useSecState(0);
  const [t1, setT1] = useSecState("");
  const [t2, setT2] = useSecState("");
  const [blink, setBlink] = useSecState(true);

  useSecEffect(() => {
    const i = setInterval(() => setBlink(b => !b), 530);
    return () => clearInterval(i);
  }, []);

  useSecEffect(() => {
    if (!inView || step > 0) return;
    setStep(1);
  }, [inView]);

  useSecEffect(() => {
    if (step !== 1) return;
    setT1(""); let i = 0;
    const tick = () => { i++; setT1("whoami".slice(0,i)); if (i < 6) setTimeout(tick, 75 + Math.random()*40); else setTimeout(() => setStep(2), 280); };
    setTimeout(tick, 500);
  }, [step === 1]);

  useSecEffect(() => {
    if (step !== 2) return;
    const t = setTimeout(() => setStep(3), 700);
    return () => clearTimeout(t);
  }, [step]);

  useSecEffect(() => {
    if (step !== 3) return;
    setT2(""); let i = 0; const cmd = "neofetch";
    const tick = () => { i++; setT2(cmd.slice(0,i)); if (i < cmd.length) setTimeout(tick, 70 + Math.random()*35); else setTimeout(() => setStep(4), 280); };
    setTimeout(tick, 300);
  }, [step === 3]);

  const WHO_OUT = lang === "en"
    ? "ege-turanoglu // Full-stack Developer · Izmir, TR"
    : "ege-turanoglu // Full-stack Geliştirici · İzmir, TR";

  const INFO = lang === "en" ? [
    ["user",   "ege@izmir"],
    ["role",   "Full-stack Developer"],
    ["exp",    "1+ year"],
    ["stack",  "TypeScript · React · AI"],
    ["status", "● open to work"],
    ["edu",    "CompEng, IYTE · 2026"],
  ] : [
    ["user",   "ege@izmir"],
    ["role",   "Full-stack Geliştirici"],
    ["exp",    "1+ yıl"],
    ["stack",  "TypeScript · React · AI"],
    ["status", "● çalışmaya hazır"],
    ["edu",    "Bilg. Müh., İYTE · 2026"],
  ];

  const ASCII = ["████  ████ ", "█     █    ", "███   ███  ", "█     █    ", "████  ████ "];
  const VOLT = "#B2F500";
  const KEY_C = "#FF5B14";
  const BG = "rgba(8,8,9,0.97)";
  const BAR = "rgba(20,20,22,0.99)";
  const FG = "#E0E0E0";
  const DIM = "#686868";
  const CUR = { display:"inline-block", width:8, height:14, background: blink ? FG : "transparent", verticalAlign:"text-bottom", marginLeft:2 };

  return (
    <div ref={ref} style={{
      fontFamily: "var(--font-mono)",
      fontSize: 13,
      lineHeight: 1.5,
      borderRadius: 12,
      overflow: "hidden",
      border: "1px solid rgba(255,255,255,0.07)",
      boxShadow: "0 40px 80px rgba(0,0,0,0.55), 0 0 0 1px rgba(255,255,255,0.03)",
      background: BG,
      userSelect: "none",
    }}>
      {/* Title bar */}
      <div style={{ padding: "11px 16px", background: BAR, display: "flex", alignItems: "center", gap: 8, borderBottom: "1px solid rgba(255,255,255,0.05)" }}>
        <span style={{ display:"flex", gap:6 }}>
          {["#FF5F57","#FEBC2E","#28C840"].map((c,i) => <span key={i} style={{ width:12, height:12, borderRadius:"50%", background:c, display:"inline-block" }} />)}
        </span>
        <span style={{ flex:1, textAlign:"center", fontSize:12, color:DIM, letterSpacing:"0.02em" }}>
          ege@portfolio: ~/portfolio — zsh
        </span>
      </div>

      {/* Body */}
      <div style={{ padding:"20px 20px 22px", minHeight: 260 }}>
        {/* whoami prompt */}
        <div style={{ display:"flex", marginBottom: step >= 2 ? 4 : 0 }}>
          <span style={{ color:VOLT, whiteSpace:"nowrap", marginRight:4 }}>ege@portfolio:~$</span>
          <span style={{ color:FG }}>{t1}{step <= 1 && <span style={CUR}/>}</span>
        </div>

        {/* whoami output */}
        {step >= 2 && (
          <div style={{ color:DIM, marginBottom:16, paddingLeft:2 }}>{WHO_OUT}</div>
        )}

        {/* neofetch prompt */}
        {step >= 3 && (
          <div style={{ display:"flex", marginBottom: step >= 4 ? 14 : 0 }}>
            <span style={{ color:VOLT, whiteSpace:"nowrap", marginRight:4 }}>ege@portfolio:~$</span>
            <span style={{ color:FG }}>{t2}{step === 3 && <span style={CUR}/>}</span>
          </div>
        )}

        {/* neofetch output */}
        {step >= 4 && (
          <div style={{ display:"flex", gap:20, marginBottom:16, alignItems:"flex-start" }}>
            {/* ASCII art */}
            <div style={{ color:VOLT, letterSpacing:"0.01em", flexShrink:0 }}>
              {ASCII.map((line, i) => (
                <StaggerLine key={i} delay={i * 55}>{line}</StaggerLine>
              ))}
            </div>
            {/* Info */}
            <div style={{ paddingTop:2 }}>
              {INFO.map(([key, val], i) => (
                <StaggerLine key={key} delay={(ASCII.length + i) * 55}>
                  <span style={{ color:KEY_C, display:"inline-block", minWidth:54 }}>{key}:</span>
                  {val.startsWith("●")
                    ? <span><span style={{ color:VOLT }}>●</span><span style={{ color:FG }}>{val.slice(1)}</span></span>
                    : <span style={{ color:FG }}>{val}</span>
                  }
                </StaggerLine>
              ))}
            </div>
          </div>
        )}

        {/* idle cursor */}
        {step >= 4 && (
          <StaggerLine delay={(ASCII.length + INFO.length) * 55 + 100}>
            <span style={{ color:VOLT }}>ege@portfolio:~$</span>
            <span style={CUR}/>
          </StaggerLine>
        )}
      </div>
    </div>
  );
}

// ---------- Hero -----------------------------------------------------------

function Hero({ onScrollNext }) {
  const { lang, t } = React.useContext(window.LangContext);
  const isWide = useIsWide();
  const isMobile = window.useIsMobile();
  return (
    <section id="top" style={{
      minHeight: "100vh",
      display: "flex",
      flexDirection: "column",
      justifyContent: "space-between",
      padding: isMobile ? "100px 16px 40px" : "clamp(140px, 16vh, 200px) clamp(20px, 4vw, 56px) 56px",
      position: "relative",
      maxWidth: "var(--max-content)",
      marginInline: "auto",
      width: "100%",
      boxSizing: "border-box",
    }}>
      <Reveal>
        <MetaRow items={[
          [t("hero.meta.now.label"), t("hero.meta.now.val")],
          [t("hero.meta.loc.label"), t("hero.meta.loc.val")],
          [t("hero.meta.yr.label"),  t("hero.meta.yr.val")],
        ]} />
      </Reveal>

      <div style={{
        marginTop: "auto",
        marginBottom: 40,
        display: isWide ? "grid" : "block",
        gridTemplateColumns: isWide ? "1fr min(420px, 36vw)" : undefined,
        gap: isWide ? "clamp(32px, 4vw, 72px)" : undefined,
        alignItems: "center",
      }}>
        <div>
        <TextReveal
          as="h1"
          lines={[
            t("hero.line1"),
            <React.Fragment key="l2">{t("hero.line2").replace(/\.$/, "")}<span style={{color:"var(--accent)"}}>.</span></React.Fragment>
          ]}
          style={{
            fontFamily: "var(--font-display)",
            fontWeight: 600,
            fontSize: "clamp(56px, 11vw, 168px)",
            lineHeight: 0.96,
            letterSpacing: "-0.035em",
            margin: 0,
            color: "var(--fg)",
            fontVariationSettings: '"opsz" 96',
            textWrap: "balance",
          }}
        />

        <Reveal delay={700}>
          <p style={{
            marginTop: 36,
            maxWidth: 640,
            fontSize: 19,
            lineHeight: 1.55,
            color: "var(--fg-muted)",
            textWrap: "pretty",
          }}>
            {t("hero.desc")}
          </p>
        </Reveal>

        <Reveal delay={900}>
          <div style={{ marginTop: 40, display: "flex", gap: 14, alignItems: "center", flexWrap: "wrap" }}>
            <MagneticButton
              data-magnetic="true"
              onClick={() => onScrollNext && onScrollNext()}
              style={{
                background: "var(--accent)",
                color: "var(--accent-fg)",
                border: "none",
                padding: "16px 26px",
                borderRadius: "var(--radius-2)",
                fontFamily: "var(--font-mono)",
                fontSize: 13,
                letterSpacing: "0.1em",
                textTransform: "uppercase",
                cursor: "pointer",
                fontWeight: 500,
                display: "inline-flex",
                alignItems: "center",
                gap: 10,
              }}
              onMouseEnter={(e) => { e.currentTarget.style.boxShadow = "var(--shadow-signal)"; }}
              onMouseLeave={(e) => { e.currentTarget.style.boxShadow = "none"; }}
            >
              {t("hero.cta.work")}
              <span style={{ display: "inline-block" }}>→</span>
            </MagneticButton>
            <a
              href="mailto:egeturanoglu@gmail.com"
              style={{
                padding: "16px 4px",
                fontFamily: "var(--font-mono)",
                fontSize: 13,
                letterSpacing: "0.1em",
                textTransform: "uppercase",
                color: "var(--fg)",
                borderBottom: "1px solid var(--fg-faint)",
                transition: "border-color 200ms, color 200ms",
              }}
              onMouseEnter={(e) => { e.currentTarget.style.borderColor = "var(--accent)"; e.currentTarget.style.color = "var(--accent)"; }}
              onMouseLeave={(e) => { e.currentTarget.style.borderColor = "var(--fg-faint)"; e.currentTarget.style.color = "var(--fg)"; }}
            >
              {t("hero.cta.contact")}
            </a>
          </div>
        </Reveal>
        </div>{/* end left col */}

        {/* Right col — Terminal */}
        {isWide && (
          <Reveal delay={500} y={24}>
            <TerminalWindow />
          </Reveal>
        )}
      </div>

      <div style={{
        display: "flex",
        justifyContent: "space-between",
        alignItems: "flex-end",
        fontFamily: "var(--font-mono)",
        fontSize: 11,
        letterSpacing: "0.12em",
        color: "var(--fg-faint)",
        textTransform: "uppercase",
      }}>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 10 }}>
          <span style={{ width: 8, height: 8, borderRadius: "50%", background: "var(--volt-500)", display: "inline-block", boxShadow: "0 0 0 3px rgba(178,245,0,0.18)", animation: "voltPulse 2s ease-in-out infinite" }} />
          {t("hero.status")}
        </span>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 10 }}>
          scroll
          <span style={{ width: 1, height: 32, background: "var(--fg-faint)", display: "inline-block", animation: "scrollHint 2s ease-in-out infinite" }} />
        </span>
      </div>
    </section>
  );
}

// ---------- About ----------------------------------------------------------

function About() {
  const { lang, t } = React.useContext(window.LangContext);
  const isMobile = window.useIsMobile();
  return (
    <section id="about" data-screen-label="03 About" style={{
      padding: isMobile ? "48px 16px" : "clamp(80px, 12vh, 160px) clamp(20px, 4vw, 56px)",
      maxWidth: "var(--max-content)",
      marginInline: "auto",
      width: "100%",
      boxSizing: "border-box",
    }}>
      <SectionHeader
        number="03"
        eyebrow={t("about.eyebrow")}
        title={t("about.title")}
      />

      <AboutContent />
    </section>
  );
}

function AboutContent() {
  const { lang, t } = React.useContext(window.LangContext);
  const isMobile = window.useIsMobile();
  return (
    <div style={{
      display: "grid",
      gridTemplateColumns: isMobile ? "1fr" : "120px 1fr 1fr",
      gap: isMobile ? 28 : "clamp(20px, 4vw, 56px)",
      alignItems: "start",
    }}>
      {!isMobile && <div />}
      <Reveal delay={100}>
        <div style={{ position: "relative" }}>
          <img
            src="../../assets/avatar.jpeg"
            alt="Ege Turanoğlu"
            style={{
              width: "100%",
              aspectRatio: isMobile ? "16 / 9" : "4 / 5",
              objectFit: "cover",
              borderRadius: "var(--radius-3)",
              filter: "saturate(1.04)",
            }}
          />
          <div style={{
            position: "absolute",
            bottom: 16, left: 16,
            padding: "4px 10px",
            background: "rgba(10,10,11,0.78)",
            backdropFilter: "blur(8px)",
            fontFamily: "var(--font-mono)",
            fontSize: 11,
            letterSpacing: "0.1em",
            textTransform: "uppercase",
            color: "var(--paper-100)",
            borderRadius: 999,
          }}>
            <span style={{ color: "var(--volt-500)" }}>●</span> IZMIR, 2026
          </div>
        </div>
      </Reveal>
      <div style={{ display: "flex", flexDirection: "column", gap: 36 }}>
        <Reveal delay={200}>
          <p style={{
            fontFamily: "var(--font-display)",
            fontWeight: 500,
            fontSize: "clamp(20px, 2.2vw, 30px)",
            lineHeight: 1.32,
            letterSpacing: "-0.015em",
            color: "var(--fg)",
            textWrap: "pretty",
            margin: 0,
          }}>
            "{t("about.quote.pre")}<em style={{fontStyle:"italic", color:"var(--accent)"}}>{t("about.quote.em")}</em>{t("about.quote.post")}"
          </p>
        </Reveal>
        <Reveal delay={300}>
          <p style={{ fontSize: 16, lineHeight: 1.7, color: "var(--fg-muted)", margin: 0 }}>
            {t("about.bio")}
          </p>
        </Reveal>
        <Reveal delay={400}>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 24, paddingTop: 18, borderTop: "var(--border-hairline)" }}>
            <Stat k={t("about.stat.years.k")}  v={t("about.stat.years.v")} />
            <Stat k={t("about.stat.stack.k")}  v={t("about.stat.stack.v")} />
            <Stat k={t("about.stat.latest.k")} v={t("about.stat.latest.v")} />
            <Stat k={t("about.stat.edu.k")}    v={t("about.stat.edu.v")} />
          </div>
        </Reveal>
      </div>
    </div>
  );
}

function Stat({ k, v }) {
  return (
    <div>
      <div className="eyebrow" style={{ marginBottom: 6 }}>{k}</div>
      <div style={{ fontFamily: "var(--font-mono)", fontSize: 14, color: "var(--fg)", letterSpacing: "0.02em" }}>{v}</div>
    </div>
  );
}

// ---------- Work -----------------------------------------------------------

const WORK = [
  {
    company: "Brew Interactive",
    role: "Full-Stack Developer · Software Specialist",
    location: "Izmir, Turkey",
    period: "Dec 2024 — May 2026",
    status: "archived",
    bullets: [
      "Worked across corporate and internal projects as a software specialist, both independently and as part of product teams.",
      "Took team leadership responsibilities on selected projects while improving project management, communication, and collaboration workflows.",
      "Built HermesAI, an AI meeting assistant that joins meetings, generates summaries, extracts work items, manages integrations, and runs background tasks with LangChain and Gemini.",
      "Developed CMS-based websites, lead-generation flows, GraphQL integrations, Storybook workflows, dashboards, charts, and reporting interfaces.",
      "Built a Directus-based CMS infrastructure for KocSistem with schema snapshots, media/content modeling, PostgreSQL, Docker, and deployment-ready workflows.",
      "Contributed to responsive platforms including Pronto Radio, Interworld, TalentCard, Koc websites, Onlayer, and internal automation tools.",
    ],
    stack: ["TypeScript", "React", "Remix", "Next.js", "Directus", "GraphQL", "Drizzle ORM", "PostgreSQL", "Docker", "LangChain", "Gemini"],
  },
  {
    company: "Faurecia FORVIA",
    role: "Full-Stack Developer Intern",
    location: "Bursa, Turkey",
    period: "Jun 2024 — Aug 2024",
    status: "archived",
    bullets: [
      "Developed FILS, a React and Remix-based web application designed to simplify the internship onboarding process.",
      "Built frontend flows and connected the application to MySQL-backed data storage.",
      "Worked with different departments and learned how project management is handled inside a corporate environment.",
    ],
    stack: ["React", "Remix", "JavaScript", "MySQL"],
  },
];

function Work() {
  const { lang, t } = React.useContext(window.LangContext);
  const isMobile = window.useIsMobile();
  return (
    <section id="work" data-screen-label="01 Work" style={{
      padding: isMobile ? "48px 16px" : "clamp(80px, 12vh, 160px) clamp(20px, 4vw, 56px)",
      maxWidth: "var(--max-content)",
      marginInline: "auto",
      width: "100%",
      boxSizing: "border-box",
    }}>
      <SectionHeader
        number="01"
        eyebrow={t("work.eyebrow")}
        title={t("work.title")}
        kicker={t("work.kicker")}
      />

      <div style={{ display: "flex", flexDirection: "column", gap: 0 }}>
        {WORK.map((w, i) => <WorkItem key={i} item={w} index={i} />)}
      </div>
    </section>
  );
}

function WorkItem({ item, index }) {
  const isMobile = window.useIsMobile();
  return (
    <Reveal delay={index * 100}>
      <article style={{
        display: "grid",
        gridTemplateColumns: isMobile ? "1fr" : "120px 1fr 1fr",
        gap: isMobile ? 20 : "clamp(20px, 4vw, 56px)",
        alignItems: "start",
        padding: isMobile ? "32px 0" : "48px 0",
        borderTop: "var(--border-hairline)",
        ...(index === WORK.length - 1 ? { borderBottom: "var(--border-hairline)" } : {}),
      }}>
        <div>
          <Icon name="briefcase" size={14} style={{ color: "var(--fg-faint)", display: "block", marginBottom: 10 }} />
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--fg-faint)", letterSpacing: "0.08em", whiteSpace: isMobile ? "nowrap" : "normal" }}>
            {isMobile ? item.period : (
              <>{item.period.split(" — ")[0]}<br />— {item.period.split(" — ")[1]}</>
            )}
          </div>
        </div>

        <div>
          <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 6 }}>
            <h3 style={{
              fontFamily: "var(--font-display)",
              fontWeight: 600,
              fontSize: "clamp(28px, 3vw, 40px)",
              letterSpacing: "-0.02em",
              lineHeight: 1.05,
              margin: 0,
              color: "var(--fg)",
            }}>{item.company}</h3>
          </div>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 13, color: "var(--fg-muted)", letterSpacing: "0.02em", marginBottom: 4 }}>
            {item.role}
          </div>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--fg-faint)", letterSpacing: "0.08em", textTransform: "uppercase" }}>
            {item.location}
          </div>

          <div style={{ display: "flex", gap: 6, flexWrap: "wrap", marginTop: 28 }}>
            {item.stack.map((t) => (
              <span key={t} style={{
                padding: "4px 9px",
                border: "var(--border-hairline)",
                borderRadius: "var(--radius-2)",
                fontFamily: "var(--font-mono)",
                fontSize: 11,
                letterSpacing: "0.02em",
                color: "var(--fg-muted)",
              }}>{t}</span>
            ))}
          </div>
        </div>

        <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 14 }}>
          {item.bullets.map((b, j) => (
            <li key={j} style={{ display: "flex", gap: 14, alignItems: "flex-start" }}>
              <span style={{
                marginTop: 10,
                width: 10, height: 1,
                background: "var(--accent)",
                flexShrink: 0,
              }} />
              <span style={{ fontSize: 15, lineHeight: 1.55, color: "var(--fg-muted)" }}>{b}</span>
            </li>
          ))}
        </ul>
      </article>
    </Reveal>
  );
}

// ---------- Projects ------------------------------------------------------

// ---------- ProjectTerminal ------------------------------------------------

const FEATURED_PROJECT_EN = [
  { t: "cmd",     v: "cat reportly/README.md" },
  { t: "kv",      k: "project", v: "Reportly" },
  { t: "kv",      k: "type",    v: "Thesis project" },
  { t: "kv",      k: "role",    v: "Full-stack · AI agent" },
  { t: "kv",      k: "stack",   v: "React Native · Python · Express · FastAPI · Docker · Postgres" },
  { t: "blank" },
  { t: "comment", v: "# AI agent for SQL-based reporting" },
  { t: "text",    v: "Built an AI agent that connects to databases and generates" },
  { t: "text",    v: "SQL-based reports for technical and non-technical users." },
  { t: "text",    v: "Exports reports as PDF or CSV and reduces operational workload" },
  { t: "text",    v: "for ERP reporting flows." },
  { t: "blank" },
  { t: "comment", v: "# Related shipped work" },
  { t: "bullet",  v: "HermesAI: AI meeting assistant with summaries and work-item extraction" },
  { t: "bullet",  v: "Foodbud: social mobile app with matching, profiles, APIs, and email flows" },
  { t: "bullet",  v: "Shopper Scrapper: AI inventory comparison and recommendation tool" },
  { t: "bullet",  v: "3D Car Showroom: open-source Three.js exploration project" },
  { t: "blank" },
  { t: "kv",      k: "status",  v: "● online" },
];

const FEATURED_PROJECT_TR = [
  { t: "cmd",     v: "cat reportly/README.md" },
  { t: "kv",      k: "proje",   v: "Reportly" },
  { t: "kv",      k: "tür",     v: "Tez projesi" },
  { t: "kv",      k: "rol",     v: "Full-stack · AI agent" },
  { t: "kv",      k: "yığın",   v: "React Native · Python · Express · FastAPI · Docker · Postgres" },
  { t: "blank" },
  { t: "comment", v: "# SQL tabanlı raporlama için AI agent" },
  { t: "text",    v: "Bağlanan veritabanlarından SQL tabanlı raporlar üreten" },
  { t: "text",    v: "bir AI agent geliştirildi. Teknik ve teknik olmayan ekiplerin" },
  { t: "text",    v: "ERP raporlarını PDF veya CSV olarak almasını kolaylaştırır." },
  { t: "blank" },
  { t: "comment", v: "# İlgili işler" },
  { t: "bullet",  v: "HermesAI: toplantılara katılan, özet ve iş kalemi çıkaran AI asistanı" },
  { t: "bullet",  v: "Foodbud: eşleşme, profil, API ve e-posta akışları olan sosyal mobil app" },
  { t: "bullet",  v: "Shopper Scrapper: AI destekli envanter karşılaştırma aracı" },
  { t: "bullet",  v: "3D Car Showroom: Three.js ile açık kaynak showroom denemesi" },
  { t: "blank" },
  { t: "kv",      k: "durum",   v: "● CV'den hazırlandı" },
];

function ProjectTerminal() {
  const { lang } = React.useContext(window.LangContext);
  const [ref, inView] = useInView({ threshold: 0.1 });
  const [typed, setTyped] = useSecState("");
  const [linesVis, setLinesVis] = useSecState(0);
  const [blink, setBlink] = useSecState(true);
  const [started, setStarted] = useSecState(false);

  const lines = lang === "en" ? FEATURED_PROJECT_EN : FEATURED_PROJECT_TR;
  const CMD = lines[0].v;
  const restLines = lines.slice(1);

  useSecEffect(() => {
    const i = setInterval(() => setBlink(b => !b), 530);
    return () => clearInterval(i);
  }, []);

  useSecEffect(() => {
    if (!inView || started) return;
    setStarted(true);
    setTyped(""); setLinesVis(0);
    let i = 0;
    const tick = () => {
      i++;
      setTyped(CMD.slice(0, i));
      if (i < CMD.length) setTimeout(tick, 38 + Math.random() * 20);
      else {
        setTimeout(() => {
          let n = 0;
          const reveal = () => {
            n++;
            setLinesVis(n);
            if (n < restLines.length) setTimeout(reveal, 42);
          };
          reveal();
        }, 300);
      }
    };
    setTimeout(tick, 600);
  }, [inView]);

  // Reset when lang changes
  useSecEffect(() => {
    if (!started) return;
    setTyped(""); setLinesVis(0); setStarted(false);
  }, [lang]);

  const VOLT = "#B2F500";
  const KEY_C = "#FF5B14";
  const COMMENT_C = "#5a6a4a";
  const BG = "rgba(8,8,9,0.97)";
  const BAR = "rgba(20,20,22,0.99)";
  const FG = "#E0E0E0";
  const DIM = "#686868";
  const CUR = { display:"inline-block", width:8, height:14, background: blink ? FG : "transparent", verticalAlign:"text-bottom", marginLeft:2 };

  function renderLine(line, i) {
    if (i >= linesVis) return null;
    const delay = 0; // already staggered by linesVis counter
    const base = { opacity: 1, fontFamily: "var(--font-mono)", fontSize: 13, lineHeight: 1.65 };

    if (line.t === "blank") return <div key={i} style={{ height: 8 }} />;

    if (line.t === "kv") return (
      <div key={i} style={base}>
        <span style={{ color: KEY_C, display:"inline-block", minWidth: 68 }}>{line.k}:</span>
        {line.v.startsWith("●")
          ? <span><span style={{ color: VOLT }}>●</span><span style={{ color: FG }}>{line.v.slice(1)}</span></span>
          : <span style={{ color: FG }}>{line.v}</span>
        }
      </div>
    );

    if (line.t === "comment") return (
      <div key={i} style={{ ...base, color: COMMENT_C, fontStyle: "italic" }}>{line.v}</div>
    );

    if (line.t === "text") return (
      <div key={i} style={{ ...base, color: DIM }}>{line.v}</div>
    );

    if (line.t === "bullet") return (
      <div key={i} style={{ ...base, color: DIM, paddingLeft: 16 }}>
        <span style={{ color: VOLT, marginRight: 8 }}>→</span>{line.v}
      </div>
    );

    return null;
  }

  return (
    <Reveal delay={100}>
      <div ref={ref} style={{
        fontFamily: "var(--font-mono)",
        fontSize: 13,
        borderRadius: 12,
        overflow: "hidden",
        border: "1px solid rgba(255,255,255,0.07)",
        boxShadow: "0 32px 64px rgba(0,0,0,0.45), 0 0 0 1px rgba(255,255,255,0.03)",
        background: BG,
      }}>
        {/* Title bar */}
        <div style={{ padding:"11px 16px", background:BAR, display:"flex", alignItems:"center", gap:8, borderBottom:"1px solid rgba(255,255,255,0.05)" }}>
          <span style={{ display:"flex", gap:6 }}>
            {["#FF5F57","#FEBC2E","#28C840"].map((c,i) => <span key={i} style={{ width:12, height:12, borderRadius:"50%", background:c, display:"inline-block" }} />)}
          </span>
          <span style={{ flex:1, textAlign:"center", fontSize:12, color:DIM, letterSpacing:"0.02em" }}>
            ege@portfolio: ~/projects — zsh
          </span>
        </div>

        {/* ls output header */}
        <div style={{ padding:"16px 20px 0", color:DIM, fontSize:12, fontFamily:"var(--font-mono)" }}>
          <span style={{ color:VOLT }}>ege@portfolio:~/projects$</span>
          <span style={{ color:FG, marginLeft:6 }}>ls -la</span>
        </div>
        <div style={{ padding:"6px 20px 14px", fontFamily:"var(--font-mono)", fontSize:12, color:DIM, borderBottom:"1px solid rgba(255,255,255,0.05)" }}>
          <div>drwxr-xr-x &nbsp;<span style={{ color:"#4a9eff" }}>reportly</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style={{ color:DIM }}>AI report generation agent</span></div>
        </div>

        {/* cat command + output */}
        <div style={{ padding:"16px 20px 22px" }}>
          <div style={{ display:"flex", marginBottom:12 }}>
            <span style={{ color:VOLT, whiteSpace:"nowrap", marginRight:6 }}>ege@portfolio:~/projects$</span>
            <span style={{ color:FG }}>{typed}{linesVis === 0 && <span style={CUR}/>}</span>
          </div>

          <div>
            {restLines.map((line, i) => renderLine(line, i))}
          </div>

          {linesVis >= restLines.length && (
            <div style={{ marginTop:12 }}>
              <span style={{ color:VOLT }}>ege@portfolio:~/projects$</span>
              <span style={CUR}/>
            </div>
          )}
        </div>
      </div>
    </Reveal>
  );
}

const PROJECTS_FROM_CV = [
  {
    name: "FILS",
    origin: "Faurecia FORVIA",
    type: "Internship platform",
    period: "2024",
    summary: {
      en: "Learning platform built to simplify the internship onboarding process for new interns.",
      tr: "Yeni stajyerlerin onboarding surecini kolaylastirmak icin gelistirilen ogrenme platformu.",
    },
    bullets: {
      en: ["React and Remix flows", "MySQL-backed storage", "Department collaboration"],
      tr: ["React ve Remix akislar", "MySQL destekli veri yapisi", "Departmanlarla ortak calisma"],
    },
    stack: ["React Native", "JavaScript", "Remix", "MySQL"],
  },
  {
    name: "Pronto Radio",
    origin: "Brew Interactive",
    type: "Online radio platform",
    period: "2024-2026",
    summary: {
      en: "Responsive radio platform with station search, listening flows, favorites, discovery, user lists, and data-driven UI behavior.",
      tr: "Istasyon arama, dinleme akislari, favoriler, kesif, kullanici listeleri ve veri odakli UI davranislari olan responsive radyo platformu.",
    },
    bullets: {
      en: ["Station search and listening flows", "Favorites and user lists", "Data-driven responsive UI"],
      tr: ["Istasyon arama ve dinleme akislar", "Favoriler ve kullanici listeleri", "Veri odakli responsive UI"],
    },
    stack: ["TypeScript", "React", "i18n", "Remix", "Drizzle ORM", "PostgreSQL", "SQLite", "Tailwind CSS", "Turbo"],
  },
  {
    name: "Interworld",
    origin: "Brew Interactive",
    type: "Corporate web platform",
    period: "2024-2026",
    summary: {
      en: "Frontend experiences for reservation, contact, localization, metadata/SEO, responsive pages, and operational UI workflows.",
      tr: "Rezervasyon, iletisim, lokalizasyon, metadata/SEO, responsive sayfalar ve operasyonel UI akislarina odaklanan frontend calismalari.",
    },
    bullets: {
      en: ["Reservation and contact flows", "Localization and SEO metadata", "Operational UI workflows"],
      tr: ["Rezervasyon ve iletisim akislar", "Lokalizasyon ve SEO metadata", "Operasyonel UI akislar"],
    },
    stack: ["TypeScript", "React", "i18n", "Remix", "Next.js", "Tailwind CSS", "Drizzle ORM", "MJML", "ResendAPI"],
  },
  {
    name: "TalentCard / Koc Websites",
    origin: "Brew Interactive",
    type: "Corporate web work",
    period: "2024-2026",
    summary: {
      en: "Comparison flows, employee cards, responsive layouts, sticky headers, search/detail screens, shared UI components, and maintenance work for Koc websites.",
      tr: "Karsilastirma akislar, calisan kartlari, responsive layoutlar, sticky headerlar, arama/detay ekranlari, ortak UI bilesenleri ve Koc web siteleri bakim calismalari.",
    },
    bullets: {
      en: ["Comparison and detail screens", "Shared UI components", "Mock API integration and maintenance"],
      tr: ["Karsilastirma ve detay ekranlari", "Ortak UI bilesenleri", "Mock API entegrasyonu ve bakim"],
    },
    stack: ["Next.js", "React", "TypeScript", "Tailwind CSS", "shadcn/ui", "Express"],
  },
  {
    name: "3D Car Showroom",
    origin: "Personal",
    type: "Open-source exploration",
    period: "Personal",
    summary: {
      en: "Open-source car showroom application built with Three.js to explore new design libraries and reusable visual patterns.",
      tr: "Three.js ile yeni tasarim kutuphanelerini ve tekrar kullanilabilir gorsel kaliplari denemek icin gelistirilen acik kaynak araba showroom uygulamasi.",
    },
    bullets: {
      en: ["Three.js showroom experience", "Design library exploration", "Reusable visual experiments"],
      tr: ["Three.js showroom deneyimi", "Tasarim kutuphanesi denemeleri", "Tekrar kullanilabilir gorsel denemeler"],
    },
    stack: ["Remix", "React", "TypeScript", "Three.js"],
  },
  {
    name: "HermesAI",
    origin: "Brew Interactive",
    type: "AI meeting assistant",
    period: "2024-2026",
    summary: {
      en: "AI meeting assistant that joins meetings, generates summaries, extracts work items, manages integrations, and processes background tasks.",
      tr: "Toplantilara katilan, ozet ureten, is kalemleri cikaran, entegrasyonlari yoneten ve arka plan gorevleri isleyen AI toplanti asistani.",
    },
    bullets: {
      en: ["Meeting summaries and work-item extraction", "LLM workflows with LangChain and Gemini", "Background tasks and integrations"],
      tr: ["Toplanti ozetleri ve is kalemi cikarimi", "LangChain ve Gemini ile LLM akislar", "Arka plan gorevleri ve entegrasyonlar"],
    },
    stack: ["TypeScript", "React", "Remix", "Drizzle ORM", "PostgreSQL/libSQL", "Redis", "LangChain", "Gemini", "Docker", "Turbo", "Recall"],
  },
  {
    name: "Onlayer",
    origin: "Brew Interactive",
    type: "CMS + lead generation",
    period: "2024-2026",
    summary: {
      en: "CMS-based website and lead-generation features with GraphQL integrations, UI components, Storybook workflows, charts, reports, and dashboards.",
      tr: "GraphQL entegrasyonlari, UI bilesenleri, Storybook akislar, grafikler, raporlar ve dashboard elemanlari iceren CMS tabanli web sitesi ve lead-generation calismalari.",
    },
    bullets: {
      en: ["CMS website and lead generation", "GraphQL integrations", "Charts, reporting, and dashboard elements"],
      tr: ["CMS web sitesi ve lead generation", "GraphQL entegrasyonlari", "Grafikler, raporlama ve dashboard elemanlari"],
    },
    stack: ["Next.js", "React", "TypeScript", "Directus", "GraphQL", "Tailwind CSS", "Storybook", "NestJS", "Drizzle ORM"],
  },
  {
    name: "KS Directus CMS",
    origin: "Brew Interactive",
    type: "CMS infrastructure",
    period: "2024-2026",
    summary: {
      en: "Directus-based CMS infrastructure for KocSistem with schema snapshots, media/content modeling, PostgreSQL, Docker, and deployment-ready workflows.",
      tr: "KocSistem icin schema snapshotlari, medya/icerik modelleme, PostgreSQL, Docker ve deploy'a hazir akislarla gelistirilen Directus tabanli CMS altyapisi.",
    },
    bullets: {
      en: ["Schema snapshots", "Media and content modeling", "Deployment-ready Docker workflows"],
      tr: ["Schema snapshotlari", "Medya ve icerik modelleme", "Deploy'a hazir Docker akislar"],
    },
    stack: ["Directus", "PostgreSQL", "Docker", "Bun", "Turbo"],
  },
  {
    name: "Shopper Scrapper",
    origin: "Personal",
    type: "AI inventory comparison",
    period: "Personal",
    summary: {
      en: "AI-powered inventory comparison tool that scrapes listings, compares current products with newer alternatives, and recommends logical replacements.",
      tr: "Online ilanlari tarayan, mevcut urunleri yeni alternatiflerle karsilastiran ve mantikli degisim onerileri sunan AI destekli envanter karsilastirma araci.",
    },
    bullets: {
      en: ["Listing scraping", "Replacement recommendations", "Mobile and backend architecture"],
      tr: ["Ilan tarama", "Degisim onerileri", "Mobil ve backend mimarisi"],
    },
    stack: ["React Native", "TypeScript", "Express", "Docker", "Libsql", "Python", "Puppeteer", "Postgres"],
  },
  {
    name: "Foodbud",
    origin: "Personal",
    type: "Social mobile app",
    period: "Personal",
    summary: {
      en: "Social mobile application focused on bringing people together through shared dietary preferences, matchmaking, profiles, photo management, APIs, and email infrastructure.",
      tr: "Ortak beslenme tercihleri uzerinden insanlari bir araya getiren; eslesme, profil, fotograf yonetimi, API ve e-posta altyapisina sahip sosyal mobil uygulama.",
    },
    bullets: {
      en: ["Matchmaking flows", "Profile and photo management", "Backend/API and email infrastructure"],
      tr: ["Eslesme akislar", "Profil ve fotograf yonetimi", "Backend/API ve e-posta altyapisi"],
    },
    stack: ["React Native", "Expo", "TypeScript", "Express", "Drizzle ORM", "MJML", "Resend", "Docker", "Postgres"],
  },
  {
    name: "Reportly",
    origin: "Thesis Project",
    type: "AI reporting agent",
    period: "2026",
    summary: {
      en: "AI agent that generates SQL-based reports as PDF or CSV from connected databases for technical and non-technical ERP reporting flows.",
      tr: "Baglanan veritabanlarindan PDF veya CSV formatinda SQL tabanli raporlar ureten; teknik ve teknik olmayan ERP raporlama akislarini kolaylastiran AI agent.",
    },
    bullets: {
      en: ["Connected database reporting", "PDF and CSV exports", "Reduced operational reporting workload"],
      tr: ["Bagli veritabani raporlama", "PDF ve CSV ciktilari", "Azaltilmis operasyonel raporlama yuku"],
    },
    stack: ["React Native", "Python", "Express", "FastAPI", "Docker", "Postgres"],
  },
];

const projectNavButtonStyle = {
  appearance: "none",
  border: "var(--border-hairline)",
  background: "transparent",
  color: "var(--fg)",
  borderRadius: "var(--radius-2)",
  padding: "10px 14px",
  fontFamily: "var(--font-mono)",
  fontSize: 12,
  letterSpacing: "0.08em",
  textTransform: "uppercase",
  cursor: "pointer",
  transition: "border-color 220ms cubic-bezier(0.16,1,0.3,1), background 220ms cubic-bezier(0.16,1,0.3,1), color 220ms cubic-bezier(0.16,1,0.3,1), transform 220ms cubic-bezier(0.16,1,0.3,1)",
};

function ProjectPager() {
  const { lang } = React.useContext(window.LangContext);
  const isMobile = window.useIsMobile();
  const [active, setActive] = useSecState(0);
  const project = PROJECTS_FROM_CV[active];
  const total = PROJECTS_FROM_CV.length;
  const language = lang === "tr" ? "tr" : "en";
  const copy = language === "tr"
    ? { source: "CV projeleri", tech: "Teknolojiler", notes: "Proje notlari", prev: "Onceki", next: "Sonraki" }
    : { source: "CV projects", tech: "Technologies", notes: "Build notes", prev: "Prev", next: "Next" };

  function go(delta) {
    setActive((curr) => (curr + delta + total) % total);
  }

  return (
    <Reveal delay={100}>
      <div style={{
        borderTop: "var(--border-hairline)",
        borderBottom: "var(--border-hairline)",
        display: "grid",
        gridTemplateColumns: isMobile ? "1fr" : "minmax(220px, 0.34fr) 1fr",
        minHeight: isMobile ? "auto" : 520,
      }}>
        <div style={{
          borderRight: isMobile ? "none" : "var(--border-hairline)",
          borderBottom: isMobile ? "var(--border-hairline)" : "none",
          padding: isMobile ? "14px 0" : "24px 24px 24px 0",
          display: "flex",
          flexDirection: isMobile ? "row" : "column",
          gap: isMobile ? 8 : 4,
          overflowX: isMobile ? "auto" : "visible",
        }}>
          {PROJECTS_FROM_CV.map((p, i) => {
            const selected = i === active;
            return (
              <button
                key={p.name}
                type="button"
                onClick={() => setActive(i)}
                style={{
                  appearance: "none",
                  border: "none",
                  borderLeft: !isMobile && selected ? "2px solid var(--accent)" : "2px solid transparent",
                  background: selected ? "var(--bg-card)" : "transparent",
                  color: selected ? "var(--fg)" : "var(--fg-muted)",
                  padding: isMobile ? "10px 12px" : "13px 14px",
                  borderRadius: isMobile ? "var(--radius-2)" : "0 var(--radius-2) var(--radius-2) 0",
                  textAlign: "left",
                  fontFamily: "var(--font-mono)",
                  cursor: "pointer",
                  minWidth: isMobile ? 170 : "auto",
                  transform: selected ? (isMobile ? "translateY(-2px)" : "translateX(4px)") : "none",
                  boxShadow: selected ? "inset 0 1px 0 color-mix(in oklab, var(--fg) 8%, transparent)" : "none",
                  transition: "background 260ms cubic-bezier(0.16,1,0.3,1), color 260ms cubic-bezier(0.16,1,0.3,1), border-color 260ms cubic-bezier(0.16,1,0.3,1), transform 260ms cubic-bezier(0.16,1,0.3,1), box-shadow 260ms cubic-bezier(0.16,1,0.3,1)",
                }}
              >
                <span style={{ display: "block", fontSize: 11, color: selected ? "var(--accent)" : "var(--fg-faint)", letterSpacing: "0.08em" }}>
                  {String(i + 1).padStart(2, "0")} / {String(total).padStart(2, "0")}
                </span>
                <span style={{ display: "block", marginTop: 5, fontSize: 13, lineHeight: 1.3 }}>
                  {p.name}
                </span>
              </button>
            );
          })}
        </div>

        <article style={{
          padding: isMobile ? "28px 0 0" : "34px 0 34px clamp(28px, 4vw, 56px)",
          display: "flex",
          flexDirection: "column",
          justifyContent: "space-between",
          gap: 34,
        }}>
          <div
            key={`${project.name}-hero`}
            style={{
              animation: "projectPanelIn 360ms cubic-bezier(0.16,1,0.3,1) both",
            }}
          >
            <div className="eyebrow" style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 18 }}>
              <span style={{ color: "var(--accent)" }}>{copy.source}</span>
              <span style={{ width: 28, height: 1, background: "var(--border-loud)", display: "inline-block" }} />
              <span>{project.origin}</span>
            </div>
            <h3 style={{
              fontFamily: "var(--font-display)",
              fontWeight: 600,
              fontSize: "clamp(38px, 6vw, 88px)",
              letterSpacing: "-0.035em",
              lineHeight: 0.98,
              color: "var(--fg)",
              margin: 0,
            }}>
              {project.name}
            </h3>
            <div style={{ marginTop: 18 }}>
              <MetaRow items={[[project.type, project.period], [copy.source, `${active + 1}/${total}`]]} />
            </div>
            <p style={{
              maxWidth: 780,
              margin: "30px 0 0",
              fontSize: isMobile ? 17 : 20,
              lineHeight: 1.55,
              color: "var(--fg-muted)",
              textWrap: "pretty",
            }}>
              {project.summary[language]}
            </p>
          </div>

          <div
            key={`${project.name}-details`}
            style={{
            display: "grid",
            gridTemplateColumns: isMobile ? "1fr" : "1fr 1fr",
            gap: isMobile ? 28 : 44,
            animation: "projectPanelIn 420ms cubic-bezier(0.16,1,0.3,1) 60ms both",
          }}>
            <div>
              <div className="eyebrow" style={{ marginBottom: 14 }}>{copy.notes}</div>
              <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 12 }}>
              {project.bullets[language].map((b, i) => (
                  <li key={b} style={{ display: "flex", gap: 12, alignItems: "flex-start", color: "var(--fg-muted)", fontSize: 15, lineHeight: 1.55, animation: `projectListIn 300ms cubic-bezier(0.16,1,0.3,1) ${90 + i * 45}ms both` }}>
                    <span style={{ marginTop: 10, width: 14, height: 1, background: "var(--accent)", flexShrink: 0 }} />
                    <span>{b}</span>
                  </li>
                ))}
              </ul>
            </div>
            <div>
              <div className="eyebrow" style={{ marginBottom: 14 }}>{copy.tech}</div>
              <div style={{ display: "flex", flexWrap: "wrap", gap: 7 }}>
                {project.stack.map((tech, i) => (
                  <span key={tech} style={{
                    padding: "6px 10px",
                    border: "var(--border-hairline)",
                    borderRadius: "var(--radius-2)",
                    fontFamily: "var(--font-mono)",
                    fontSize: 11,
                    letterSpacing: "0.02em",
                    color: "var(--fg-muted)",
                    animation: `projectPanelIn 260ms cubic-bezier(0.16,1,0.3,1) ${90 + i * 24}ms both`,
                  }}>{tech}</span>
                ))}
              </div>
            </div>
          </div>

          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 18, paddingTop: 8 }}>
            <button type="button" onClick={() => go(-1)} style={projectNavButtonStyle}>{copy.prev}</button>
            <div style={{ display: "flex", gap: 6, flexWrap: "wrap", justifyContent: "center" }}>
              {PROJECTS_FROM_CV.map((p, i) => (
                <button
                  key={p.name}
                  type="button"
                  aria-label={`Go to ${p.name}`}
                  onClick={() => setActive(i)}
                  style={{
                    width: i === active ? 24 : 7,
                    height: 7,
                    borderRadius: 99,
                    border: "none",
                    background: i === active ? "var(--accent)" : "var(--border-loud)",
                    padding: 0,
                    cursor: "pointer",
                    transform: i === active ? "translateY(-1px)" : "none",
                    transition: "width 260ms cubic-bezier(0.16,1,0.3,1), background 260ms cubic-bezier(0.16,1,0.3,1), transform 260ms cubic-bezier(0.16,1,0.3,1)",
                  }}
                />
              ))}
            </div>
            <button type="button" onClick={() => go(1)} style={projectNavButtonStyle}>{copy.next}</button>
          </div>
        </article>
      </div>
    </Reveal>
  );
}

function Projects() {
  const { lang, t } = React.useContext(window.LangContext);
  const isMobile = window.useIsMobile(); // eslint-disable-line
  return (
    <section id="projects" data-screen-label="02 Projects" style={{
      padding: isMobile ? "48px 16px" : "clamp(80px, 12vh, 160px) clamp(20px, 4vw, 56px)",
      maxWidth: "var(--max-content)",
      marginInline: "auto",
      width: "100%",
      boxSizing: "border-box",
    }}>
      <SectionHeader
        number="02"
        eyebrow={t("projects.eyebrow")}
        title={t("projects.title")}
      />

      <div style={{
        display: "grid",
        gridTemplateColumns: isMobile ? "1fr" : "120px 1fr",
        gap: isMobile ? 0 : "clamp(20px, 4vw, 56px)",
      }}>
        {!isMobile && <div />}
        <ProjectPager />
      </div>
    </section>
  );
}

// (ProjectCard kept for potential future use but not rendered)
function ProjectCard({ project: p, index }) {
  const { lang, t } = React.useContext(window.LangContext);
  const [hover, setHover] = useSecState(false);
  return null;
}

// ---------- StackMarquee --------------------------------------------------

function StackMarquee() {
  const stack = ["TypeScript", "JavaScript", "React", "Next.js", "Remix", "React Native", "Expo",
                 "Directus", "GraphQL", "Drizzle ORM", "PostgreSQL", "MySQL", "SQLite",
                 "Docker", "Express", "NestJS", "LangChain", "Gemini", "TailwindCSS"];
  // Duplicate for seamless loop
  const items = [...stack, ...stack];
  return (
    <section style={{
      padding: "48px 0",
      borderTop: "var(--border-hairline)",
      borderBottom: "var(--border-hairline)",
      overflow: "hidden",
      maskImage: "linear-gradient(to right, transparent, black 6%, black 94%, transparent)",
      WebkitMaskImage: "linear-gradient(to right, transparent, black 6%, black 94%, transparent)",
    }}>
      <div style={{
        display: "flex",
        gap: 56,
        whiteSpace: "nowrap",
        animation: "marquee 60s linear infinite",
        fontFamily: "var(--font-mono)",
        fontSize: "clamp(28px, 3vw, 44px)",
        letterSpacing: "-0.01em",
        color: "var(--fg)",
        fontWeight: 500,
        textTransform: "uppercase",
      }}>
        {items.map((s, i) => (
          <span key={i} style={{ display: "inline-flex", alignItems: "center", gap: 56 }}>
            {(i % 3 === 1) ? <span style={{ color: "var(--accent)" }}>{s}</span> : <span>{s}</span>}
            <span style={{ color: "var(--fg-faint)" }}>·</span>
          </span>
        ))}
      </div>
    </section>
  );
}

// ---------- Contact -------------------------------------------------------

function Contact() {
  const { lang, t } = React.useContext(window.LangContext);
  const isMobile = window.useIsMobile();
  return (
    <section id="contact" data-screen-label="05 Contact" style={{
      padding: isMobile ? "48px 16px" : "clamp(80px, 12vh, 160px) clamp(20px, 4vw, 56px)",
      maxWidth: "var(--max-content)",
      marginInline: "auto",
      width: "100%",
      boxSizing: "border-box",
    }}>
      <SectionHeader
        number="05"
        eyebrow={t("contact.eyebrow")}
        title={t("contact.title")}
        kicker={t("contact.kicker")}
      />

      <ContactChannels />
    </section>
  );
}

function ContactChannels() {
  const isMobile = window.useIsMobile();
  return (
    <div style={{
      display: "grid",
      gridTemplateColumns: isMobile ? "1fr" : "120px 1fr",
      gap: isMobile ? 0 : "clamp(20px, 4vw, 56px)",
    }}>
      {!isMobile && <div />}
      <Reveal delay={100}>
        <div style={{
          display: "grid",
          gridTemplateColumns: isMobile ? "1fr" : "1fr 1fr",
          columnGap: "clamp(32px, 5vw, 80px)",
          rowGap: 0,
        }}>
          <div>
            <DirectChannel label="EMAIL"  value="egeturanoglu@gmail.com" href="mailto:egeturanoglu@gmail.com" />
            <DirectChannel label="PHONE"  value="+90 534 511 07 01"      href="tel:+905345110701" />
            <DirectChannel label="GITHUB" value="github.com/egeturanoglu" href="https://github.com/egeturanoglu" />
          </div>
          <div>
            <DirectChannel label="LINKEDIN" value="linkedin.com/in/ege-turanoglu" href="https://linkedin.com/in/ege-turanoğlu-370370285/" />
            <DirectChannel label="CV"       value="EgeTuranoglu_CV.pdf"          href="../../assets/EgeTuranoglu_CV.pdf" />
          </div>
        </div>
      </Reveal>
    </div>
  );
}

function DirectChannel({ label, value, href }) {
  return (
    <a href={href} target="_blank" style={{
      display: "flex",
      flexDirection: "column",
      gap: 6,
      padding: "14px 0",
      borderBottom: "var(--border-hairline)",
      color: "var(--fg)",
      transition: "color 200ms",
    }}
    onMouseEnter={(e) => { e.currentTarget.style.color = "var(--accent)"; }}
    onMouseLeave={(e) => { e.currentTarget.style.color = "var(--fg)"; }}>
      <div className="eyebrow">{label} ↗</div>
      <div style={{ fontFamily: "var(--font-mono)", fontSize: 16, letterSpacing: "0.01em" }}>{value}</div>
    </a>
  );
}

// ---------- TechStack -------------------------------------------------------

const TECH_CATEGORIES = [
  {
    key: "backend",
    items: [
      { name: "Node.js",     slug: "nodedotjs" },
      { name: "Express",     slug: "express" },
      { name: "NestJS",      slug: "nestjs" },
      { name: "PostgreSQL",  slug: "postgresql" },
      { name: "MySQL",       slug: "mysql" },
    ],
  },
  {
    key: "frontend",
    items: [
      { name: "Next.js",      slug: "nextdotjs" },
      { name: "Remix",        slug: "remix" },
      { name: "TypeScript",   slug: "typescript" },
      { name: "React",        slug: "react" },
      { name: "React Native", slug: "react" },
      { name: "TailwindCSS",  slug: "tailwindcss" },
    ],
  },
  {
    key: "cloud",
    items: [
      { name: "Docker",         slug: "docker" },
      { name: "GitHub Actions", slug: "githubactions" },
      { name: "Bun",            slug: "bun" },
      { name: "Turbo",          slug: "turbo" },
    ],
  },
  {
    key: "integrations",
    items: [
      { name: "Directus",     slug: "directus" },
      { name: "GraphQL",      slug: "graphql" },
      { name: "Drizzle ORM",  slug: "drizzle" },
      { name: "Gemini",       slug: "googlegemini" },
      { name: "LangChain",    slug: "langchain" },
    ],
  },
];

function TechItem({ item }) {
  const { theme } = React.useContext(window.LangContext);
  const [hover, setHover] = useSecState(false);
  const [imgFailed, setImgFailed] = useSecState(false);

  const CDN = "https://cdn.jsdelivr.net/npm/simple-icons@14/icons";
  const imgSrc = item.src || (item.slug ? `${CDN}/${item.slug}.svg` : null);

  // colored=true → renkli SVG (DevIcons vb.) → grayscale/saturate filter
  // colored=false → siyah SVG (Simple Icons) → brightness/invert filter
  const iconFilter = item.colored
    ? hover
      ? "saturate(1.3) brightness(1.05)"
      : "grayscale(1) opacity(0.55)"
    : hover
      ? theme === "dark" ? "brightness(0) invert(1)" : "none"
      : theme === "dark" ? "brightness(0) invert(0.55)" : "brightness(0) opacity(0.4)";

  return (
    <div
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        display: "flex",
        alignItems: "center",
        gap: 12,
        padding: "10px 0",
        paddingLeft: hover ? 6 : 0,
        borderBottom: "var(--border-hairline)",
        cursor: "default",
        transition: "padding-left 200ms cubic-bezier(0.16,1,0.3,1)",
      }}
    >
      {imgSrc && !imgFailed ? (
        <img
          src={imgSrc}
          alt=""
          width="16" height="16"
          style={{ flexShrink: 0, display: "block", filter: iconFilter, transition: "filter 240ms ease" }}
          onError={(e) => {
            if (item.alt) {
              e.currentTarget.src = `${CDN}/${item.alt}.svg`;
              e.currentTarget.onerror = () => setImgFailed(true);
            } else {
              setImgFailed(true);
            }
          }}

        />
      ) : item.letter ? (
        <span style={{
          width: 16, height: 16, flexShrink: 0,
          display: "inline-flex", alignItems: "center", justifyContent: "center",
          fontFamily: "var(--font-mono)", fontSize: 11, fontWeight: 700,
          color: hover
            ? (theme === "dark" ? "#ffffff" : "var(--accent)")
            : (theme === "dark" ? "rgba(255,255,255,0.55)" : "rgba(0,0,0,0.4)"),
          transition: "color 240ms ease",
          lineHeight: 1,
        }}>{item.letter}</span>
      ) : (
        <span style={{
          width: 16, height: 16,
          display: "inline-flex", alignItems: "center", justifyContent: "center",
          flexShrink: 0,
        }}>
          <span style={{
            width: 8, height: 1.5,
            background: hover ? "var(--accent)" : "var(--fg-faint)",
            borderRadius: 1,
            transition: "background 200ms",
          }} />
        </span>
      )}
      <span style={{
        fontFamily: "var(--font-mono)",
        fontSize: 13,
        letterSpacing: "0.03em",
        color: hover ? "var(--fg)" : "var(--fg-muted)",
        transition: "color 200ms ease",
      }}>{item.name}</span>
    </div>
  );
}

function TechCategory({ cat, index }) {
  const { t } = React.useContext(window.LangContext);
  const [hover, setHover] = useSecState(false);

  return (
    <Reveal delay={index * 70}>
      <div
        onMouseEnter={() => setHover(true)}
        onMouseLeave={() => setHover(false)}
        style={{
          position: "relative",
          background: "var(--bg-card)",
          borderRadius: "var(--radius-4)",
          padding: "24px 28px 20px",
          overflow: "hidden",
        }}
      >
        {/* Signal accent line slides in on card hover */}
        <div style={{
          position: "absolute",
          top: 0, left: 0,
          height: 1,
          width: hover ? "100%" : "0%",
          background: "var(--accent)",
          transition: "width 480ms cubic-bezier(0.16,1,0.3,1)",
        }} />

        <div className="eyebrow" style={{
          marginBottom: 16,
          color: hover ? "var(--fg)" : "var(--fg-muted)",
          transition: "color 200ms ease",
          display: "flex",
          alignItems: "center",
          gap: 8,
        }}>
          <Icon name="layers" size={12} style={{ flexShrink: 0 }} />
          {t(`stack.cat.${cat.key}`)}
        </div>

        <div>
          {cat.items.map((item) => (
            <TechItem key={item.name} item={item} />
          ))}
        </div>
      </div>
    </Reveal>
  );
}

function TechStack() {
  const { lang, t } = React.useContext(window.LangContext);
  const isMobile = window.useIsMobile();
  return (
    <section id="stack" data-screen-label="04 Stack" style={{
      padding: isMobile ? "48px 16px" : "clamp(80px, 12vh, 160px) clamp(20px, 4vw, 56px)",
      maxWidth: "var(--max-content)",
      marginInline: "auto",
      width: "100%",
      boxSizing: "border-box",
    }}>
      <SectionHeader
        number="04"
        eyebrow={t("stack.eyebrow")}
        title={t("stack.title")}
        kicker={t("stack.kicker")}
      />

      <div style={{
        display: "grid",
        gridTemplateColumns: isMobile ? "1fr" : "120px 1fr",
        gap: isMobile ? 0 : "clamp(20px, 4vw, 56px)",
      }}>
        {!isMobile && <div />}
        <div style={{
          display: "grid",
          gridTemplateColumns: isMobile ? "1fr" : "1fr 1fr",
          gap: 14,
        }}>
          {TECH_CATEGORIES.map((cat, i) => (
            <TechCategory key={cat.key} cat={cat} index={i} />
          ))}
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Hero, About, Work, Projects, Contact, StackMarquee, SectionHeader, ProjectCard, ProjectPager, MetaRow, TechStack, TechCategory, TechItem, TerminalWindow });
