/* global React, ReactDOM, Icon, CONTACT_CONFIG */
const { useState, useEffect } = React;
const ASSET = (path) => `assets/lp/${path}`;

// ============== DATA ==============
const PROJECTS = {
  jp: [
    {
      num: "01",
      cat: "SaaS / AdTech / 0→1",
      filter: "saas",
      title: "SNS広告運用自動化SaaS（0→1立ち上げ）",
      img: "components/project_cards/all_project_01_marketing_automation_saas.webp",
      summary: "SNS広告運用を自動化するBtoB向けSaaSの0→1立ち上げを事業責任者として統括。プロダクト戦略・エンジニアリング・GTM・ポストローンチを一気通貫でオーナーシップ。",
      role: "事業責任者 / フルスタックエンジニア / PdM",
      scope: "市場分析・要件定義・アーキ設計・開発・リリース・PR・CS体制構築",
      stack: "Next.js, React, TypeScript, Hono, GCP / Cloud Run, Terraform, Turborepo, BigQuery, dbt, Airbyte",
      impact: "ヒューマンエラー最大90%・広告運用工数最大90%削減を掲げてプレスリリース配信。CS体制をゼロから構築。",
    },
    {
      num: "02",
      cat: "SaaS / HR Tech / AI / 0→1",
      filter: "saas",
      title: "AI採用評価SaaS『Enma』(個人事業 / 0→1立ち上げ中)",
      img: "components/project_cards/all_project_09_enma.webp",
      summary: "候補者の経歴・面接メモをAIが分析し、『スキル盛り・受け身作業員・ROI赤字・AI丸コピ』の4リスクを自動検出するBtoB向け採用評価SaaS。自社採用で実運用しながら継続改善中。",
      role: "個人事業主 / プロダクトオーナー / フルスタックエンジニア",
      scope: "プロダクト企画・市場分析・アーキ設計・開発・自社運用・改善",
      stack: "Next.js, React, TypeScript, AI / LLM 連携, クラウド",
      impact: "AIで候補者の主張と実態のギャップを検出。面接で確認すべき質問・適正報酬まで自動生成。早期導入パートナー募集中。",
    },
    {
      num: "03",
      cat: "Web管理画面 / 0→1 リビルド",
      filter: "tooling",
      title: "美容系マッチングプラットフォーム管理画面リビルド",
      img: "components/project_cards/all_project_02_ad_reporting_platform.webp",
      summary: "美容系モデル・サロンマッチングプラットフォームのWeb管理画面を責任者としてフルスクラッチでリビルド。アカウント・検索・メッセージ・課金・運営管理のコア機能を0から再構築中。",
      role: "Web管理画面責任者（業務委託）",
      scope: "フロントエンド・バックエンド・インフラのフルスタック設計・実装、モバイル/バックエンドチーム連携",
      stack: "Next.js 16, React 19, AWS Amplify, Terraform, Flutter（モバイル連携）, Go（バックエンド連携）",
      impact: "管理画面の全コア機能を0から設計・実装。Web・アプリ間の一貫したUXとAPI統合を担保。",
    },
    {
      num: "04",
      cat: "業務システム / フルスクラッチ",
      filter: "saas",
      title: "航空部品管理システムのフルスクラッチ開発",
      img: "components/project_cards/all_project_03_data_infrastructure.webp",
      summary: "航空部品管理システムをフルスクラッチで新規開発。Next.js 16（App Router / RSC）+ React 19による高パフォーマンスフロントと、Hono + Drizzle ORMによるクリーンアーキテクチャベースのREST APIを設計・実装。",
      role: "フルスタックエンジニア（業務委託）",
      scope: "要件整理、フロント実装、API設計、E2Eテスト基盤、モノレポ構築",
      stack: "Next.js 16, React 19, TypeScript, Hono, Drizzle ORM, Playwright, Turborepo",
      impact: "航空部品管理システムをゼロから構築。RSC対応フロントとクリーンアーキ採用APIを設計・実装し、E2E自動化とモノレポ構成を整備。",
    },
    {
      num: "05",
      cat: "SaaS / HR・チーム運営",
      filter: "saas",
      title: "HR / チーム運営SaaS 機能開発・基盤刷新",
      img: "components/project_cards/all_project_04_workflow_web_app.webp",
      summary: "エンタープライズ向けHR/チーム管理SaaSの新規機能開発を、要件定義からリリースまで主体的に推進。コアフレームワークのメジャーバージョンアップとCI/CDパイプライン再構築を担当。",
      role: "フルスタックエンジニア（業務委託）",
      scope: "要件定義 → 設計 → 実装 → リリース、フレームワーク移行、CI/CD再構築",
      stack: "Next.js, AWS Amplify, GitHub Actions",
      impact: "コアフレームワークのメジャーバージョンアップをダウンタイムゼロで実施。CI/CD再構築により障害対応のリードタイムを短縮。",
    },
    {
      num: "06",
      cat: "AdTech / 業務自動化",
      filter: "adtech",
      title: "広告入稿自動化システム",
      img: "components/project_cards/all_project_05_new_business_pdm.webp",
      summary: "広告運用チームの入稿業務を自動化する社内システムを新規開発・導入。広告運用工数の大幅削減とアウトソーシングコスト削減に貢献。",
      role: "フルスタックエンジニア / PM",
      scope: "要件定義・設計・実装・運用・社内導入支援",
      stack: "AWS, GCP, サーバーレス, 各広告プラットフォームAPI",
      impact: "月250時間以上の業務時間削減を実現し、アウトソーシングコスト削減にも貢献。",
    },
    {
      num: "07",
      cat: "AdTech / 配信予測",
      filter: "adtech",
      title: "広告配信シミュレーション・予測システム",
      img: "components/project_cards/all_project_06_executive_dashboard.webp",
      summary: "社内広告運用者1,000名以上が利用する広告配信のシミュレーション・予測システムを設計・開発・運用。",
      role: "フルスタックエンジニア / PM",
      scope: "システム設計、フロント・バックエンド実装、運用、ステークホルダー折衝",
      stack: "AWS, GCP, Web フロントエンド, バックエンドAPI",
      impact: "社内1,000名以上の広告運用者が利用するシステムを構築し、ナショナルクライアントの広告予算獲得に貢献。",
    },
    {
      num: "08",
      cat: "データ基盤 / 広告データ",
      filter: "data",
      title: "広告配信実績レポーティングDB基盤",
      img: "components/project_cards/all_project_07_api_automation.webp",
      summary: "AWS・GCPを活用したサーバーレスデータパイプラインを構築。複数広告プラットフォームAPIを統合し、広告配信実績を一元管理するレポーティングDB基盤を実現。",
      role: "フルスタックエンジニア / PM",
      scope: "データパイプライン設計・実装、API統合、運用",
      stack: "AWS, GCP, サーバーレスデータパイプライン, 各広告プラットフォームAPI",
      impact: "複数広告プラットフォームの計測・運用データを統合し、広告配信実績のレポーティングDB基盤を構築。",
    },
    {
      num: "09",
      cat: "EC / 決済",
      filter: "tooling",
      title: "D2C向けECカートシステム決済機能開発",
      img: "components/project_cards/all_project_08_pdm_strategy.webp",
      summary: "1,000社以上に導入されているD2C特化型ECカートシステムの開発プロジェクトにコアメンバーとして参画（長期インターン）。決済機能のバックエンド実装と新機能開発を担当。",
      role: "バックエンド／フルスタックエンジニア（長期インターン）",
      scope: "Stripe API連携の決済機能実装、Ruby on Railsによる新機能開発",
      stack: "Ruby on Rails, Stripe API, バックエンド設計",
      impact: "1,000社以上に導入されているプロダクトのコアな決済領域・新機能の開発に貢献。",
    },
  ],
  en: [
    {
      num: "01",
      cat: "SaaS / AdTech / 0→1",
      filter: "saas",
      title: "Social Ad Ops Automation SaaS (0→1)",
      img: "components/project_cards/all_project_01_marketing_automation_saas.webp",
      summary: "Owned the 0→1 launch of a B2B SaaS that automates social ad operations — strategy, engineering, GTM, and post-launch all under a single line of accountability.",
      role: "Business owner / Full-stack engineer / PdM",
      scope: "Market analysis → requirements → architecture → build → release → PR → customer success",
      stack: "Next.js, React, TypeScript, Hono, GCP / Cloud Run, Terraform, Turborepo, BigQuery, dbt, Airbyte",
      impact: "Launched with public claim of up to 90% reduction in human error and ad-ops workload. Built the customer-success function from zero.",
    },
    {
      num: "02",
      cat: "SaaS / HR Tech / AI / 0→1",
      filter: "saas",
      title: "Enma — AI-Powered Hiring Intelligence (Solo venture, 0→1)",
      img: "components/project_cards/all_project_09_enma.webp",
      summary: "B2B SaaS that uses AI to analyze candidate documents and interview notes, surfacing 4 risks (skill inflation, passive worker, ROI deficit, AI-generated content). Active in-house use, refining continuously.",
      role: "Founder / Product owner / Full-stack engineer",
      scope: "Product strategy, market analysis, architecture, build, in-house ops, iteration",
      stack: "Next.js, React, TypeScript, AI / LLM integration, Cloud",
      impact: "AI surfaces gaps between candidate claims and reality. Auto-generates interview questions and fair compensation estimates. Recruiting early-adopter partners.",
    },
    {
      num: "03",
      cat: "Web Admin / Rebuild",
      filter: "tooling",
      title: "Beauty-industry Matching Platform — Admin Rebuild",
      img: "components/project_cards/all_project_02_ad_reporting_platform.webp",
      summary: "Lead engineer rebuilding the admin web platform of a model-and-salon matching service from scratch — accounts, search, messaging, billing, and ops all reconstructed.",
      role: "Admin web lead (contract)",
      scope: "Full-stack design and build (frontend, backend, infra); coordination with mobile and backend teams",
      stack: "Next.js 16, React 19, AWS Amplify, Terraform, Flutter (mobile coord), Go (backend coord)",
      impact: "Rebuilding every core admin function from zero, with consistent UX and API integration across web and mobile.",
    },
    {
      num: "04",
      cat: "Enterprise System / Full Scratch",
      filter: "saas",
      title: "Aircraft Parts Management System — Full-Scratch Build",
      img: "components/project_cards/all_project_03_data_infrastructure.webp",
      summary: "Built an aircraft-parts management system from scratch — a Next.js 16 (App Router / RSC) + React 19 front-end paired with a clean-architecture REST API on Hono + Drizzle ORM end-to-end.",
      role: "Full-stack engineer (contract)",
      scope: "Requirements, frontend build, API design, E2E test setup, monorepo",
      stack: "Next.js 16, React 19, TypeScript, Hono, Drizzle ORM, Playwright, Turborepo",
      impact: "Aircraft-parts management system delivered from zero — RSC-based front-end and clean-architecture API, with E2E automation and a monorepo foundation.",
    },
    {
      num: "05",
      cat: "SaaS / HR & Ops",
      filter: "saas",
      title: "HR / Team Ops SaaS — Features & Platform Refresh",
      img: "components/project_cards/all_project_04_workflow_web_app.webp",
      summary: "Drove new feature work on an enterprise HR / team-management SaaS — from requirements through release — and led major framework upgrades and a CI/CD overhaul.",
      role: "Full-stack engineer (contract)",
      scope: "Requirements → design → build → release; framework migration; CI/CD rebuild",
      stack: "Next.js, AWS Amplify, GitHub Actions",
      impact: "Executed major version upgrades of core frameworks with zero downtime; rebuilt CI/CD to shorten incident response.",
    },
    {
      num: "06",
      cat: "AdTech / Internal Automation",
      filter: "adtech",
      title: "Ad Submission Automation System",
      img: "components/project_cards/all_project_05_new_business_pdm.webp",
      summary: "Built an internal system that automates submission for the ad-ops team, removing manual work and outsourcing dependency.",
      role: "Full-stack engineer / PM",
      scope: "Requirements → design → build → ops, internal rollout",
      stack: "AWS, GCP, Serverless, multiple ad-platform APIs",
      impact: "Saved 250+ hours/month of manual work and reduced outsourcing cost.",
    },
    {
      num: "07",
      cat: "AdTech / Forecasting",
      filter: "adtech",
      title: "Ad Delivery Simulation & Forecasting System",
      img: "components/project_cards/all_project_06_executive_dashboard.webp",
      summary: "Designed, built, and operated an ad-delivery simulation and forecasting system used by 1,000+ in-house ad operators.",
      role: "Full-stack engineer / PM",
      scope: "System design, frontend / backend build, operations, stakeholder management",
      stack: "AWS, GCP, web frontend, backend APIs",
      impact: "Adopted by 1,000+ in-house ad operators; directly contributed to securing budgets from national clients.",
    },
    {
      num: "08",
      cat: "Data Platform / Ads",
      filter: "data",
      title: "Ad-Delivery Reporting DB Platform",
      img: "components/project_cards/all_project_07_api_automation.webp",
      summary: "Built a serverless data pipeline on AWS / GCP that unifies measurement and ops data from multiple ad platforms into a single ad-delivery reporting database.",
      role: "Full-stack engineer / PM",
      scope: "Pipeline design and build, API integration, operations",
      stack: "AWS, GCP, serverless data pipelines, multiple ad-platform APIs",
      impact: "Consolidated ad-platform data into a single ad-delivery reporting DB — replacing fragmented per-platform reporting.",
    },
    {
      num: "09",
      cat: "E-commerce / Payments",
      filter: "tooling",
      title: "D2C E-commerce Cart System — Payments",
      img: "components/project_cards/all_project_08_pdm_strategy.webp",
      summary: "Joined as a core member of a D2C-focused e-commerce cart system used by 1,000+ companies (long-term internship). Owned Stripe-based payments work and Ruby on Rails feature development.",
      role: "Backend / Full-stack engineer (long-term intern)",
      scope: "Stripe-based payments backend; new feature development on Ruby on Rails",
      stack: "Ruby on Rails, Stripe API, backend design",
      impact: "Contributed to payments and new features on a product adopted by 1,000+ merchants.",
    },
  ],
};

const FILTERS = {
  jp: [
    { id: "all", label: "すべて" },
    { id: "saas", label: "SaaS / Web" },
    { id: "adtech", label: "AdTech / 自動化" },
    { id: "data", label: "データ基盤" },
    { id: "tooling", label: "業務改善 / EC" },
  ],
  en: [
    { id: "all", label: "All" },
    { id: "saas", label: "SaaS / Web" },
    { id: "adtech", label: "AdTech / Automation" },
    { id: "data", label: "Data Platform" },
    { id: "tooling", label: "Tooling / E-comm" },
  ],
};

// ============== HEADER ==============
function PageHeader({ lang, setLang }) {
  return (
    <header className="site-header">
      <div className="container nav">
        <a href="index.html" className="brand">
          <div className="mark">KF</div>
          <div>
            <div className="name">Kenya Fujisaki</div>
            <div className="role">Full-stack Engineer / PdM</div>
          </div>
        </a>
        <a href="index.html" className="back-link" aria-label={lang === "jp" ? "ホームに戻る" : "Back to home"}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
            <path d="M19 12H5M5 12L11 6M5 12L11 18" />
          </svg>
          <span className="label">{lang === "jp" ? "ホームに戻る" : "Back to home"}</span>
        </a>
        <div style={{ display: "flex", gap: 14, alignItems: "center" }}>
          <div className="lang-toggle" role="tablist">
            <button className={lang === "jp" ? "active" : ""} onClick={() => setLang("jp")}>JP</button>
            <button className={lang === "en" ? "active" : ""} onClick={() => setLang("en")}>EN</button>
          </div>
          <a href="index.html#contact" className="btn btn-primary btn-sm">
            {lang === "jp" ? "無料案件相談" : "Free Consult"} <span className="arrow">{Icon.arrow(14)}</span>
          </a>
        </div>
      </div>
    </header>
  );
}

// ============== HERO ==============
function ProjectsHero({ lang }) {
  const list = PROJECTS[lang];
  return (
    <section className="proj-hero">
      <div className="container">
        <div className="crumb">
          <a href="index.html">{lang === "jp" ? "ホーム" : "Home"}</a>
          <span>/</span>
          <span>{lang === "jp" ? "プロジェクト" : "Projects"}</span>
        </div>
        <h1>
          <small>ALL PROJECTS</small>
          {lang === "jp" ? "実績一覧" : "Selected work"}
        </h1>
        <p>
          {lang === "jp"
            ? "SNS広告運用自動化SaaSの0→1立ち上げ、エンタープライズSaaSの機能開発・基盤刷新、広告運用自動化システム、広告配信実績レポーティングDB基盤など、これまでに関わった代表的なプロジェクトをまとめています。会社名・プロダクト名は匿名化しています。"
            : "From the 0→1 launch of a social ad-ops automation SaaS to enterprise SaaS feature work, ad-ops automation systems, and an ad-delivery reporting DB platform — selected projects from my career. Companies and product names are anonymized."}
        </p>
        <div className="meta-row">
          <div className="item">
            <div className="lbl">{lang === "jp" ? "プロジェクト数" : "Projects"}</div>
            <div className="val">{list.length}+</div>
          </div>
          <div className="item">
            <div className="lbl">{lang === "jp" ? "活動期間" : "Duration"}</div>
            <div className="val">{lang === "jp" ? "2020 — 現在" : "2020 — Present"}</div>
          </div>
          <div className="item">
            <div className="lbl">{lang === "jp" ? "支援領域" : "Domains"}</div>
            <div className="val">SaaS / AdTech / Data / 0→1</div>
          </div>
          <div className="item">
            <div className="lbl">{lang === "jp" ? "形態" : "Engagement"}</div>
            <div className="val">{lang === "jp" ? "正社員 / 業務委託 / インターン" : "Full-time / Contract / Internship"}</div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ============== TOOLBAR ==============
function Toolbar({ lang, active, setActive }) {
  const filters = FILTERS[lang];
  const list = PROJECTS[lang];
  return (
    <div className="proj-toolbar">
      <div className="container">
        <div className="filters">
          {filters.map((f) => {
            const count = f.id === "all" ? list.length : list.filter((p) => p.filter === f.id).length;
            return (
              <button
                key={f.id}
                className={`filter-pill ${active === f.id ? "active" : ""}`}
                onClick={() => setActive(f.id)}
              >
                {f.label}<span className="count">{count}</span>
              </button>
            );
          })}
        </div>
      </div>
    </div>
  );
}

// ============== GRID ==============
function ProjectGrid({ lang, active }) {
  const list = PROJECTS[lang];
  const filtered = active === "all" ? list : list.filter((p) => p.filter === active);
  return (
    <section className="all-projects">
      <div className="container">
        <div className="all-grid">
          {filtered.map((p, i) => (
            <article className="all-card" key={p.num} style={{ animation: `fadeUp .6s ease ${i*60}ms both` }}>
              <div className="img-wrap">
                <img src={ASSET(p.img)} alt={p.title} loading="lazy" />
                <div className="num-badge">PROJECT {p.num}</div>
                <div className="cat-badge">{p.cat}</div>
              </div>
              <div className="body">
                <h3>{p.title}</h3>
                <p className="summary">{p.summary}</p>
                <dl>
                  <div><dt>{lang === "jp" ? "役割" : "Role"}</dt><dd>{p.role}</dd></div>
                  <div><dt>{lang === "jp" ? "範囲" : "Scope"}</dt><dd>{p.scope}</dd></div>
                  <div><dt>{lang === "jp" ? "技術" : "Stack"}</dt><dd>{p.stack}</dd></div>
                </dl>
                <div className="impact-line">
                  <span className="ico">{lang === "jp" ? "成果" : "Impact"}</span>
                  <span>{p.impact}</span>
                </div>
              </div>
            </article>
          ))}
        </div>

        <div className="proj-cta">
          <div>
            <h3>{lang === "jp" ? "案件のご相談はお気軽に" : "Let's talk about your project"}</h3>
            <p>
              {lang === "jp"
                ? "プロダクト開発、データ基盤、AdTech、PdMアドバイザリーまで、ご相談ベースから対応可能です。"
                : "Product builds, data platforms, AdTech, and PdM advisory — happy to discuss from idea stage."}
            </p>
          </div>
          <div className="actions">
            <a href="index.html#contact" className="btn btn-primary">
              {lang === "jp" ? "無料で案件相談する" : "Get a free consultation"} <span className="arrow">{Icon.arrow(14)}</span>
            </a>
            <a href="index.html" className="btn btn-ghost">
              {lang === "jp" ? "ホームへ" : "Home"} <span className="arrow">{Icon.arrow(14)}</span>
            </a>
          </div>
        </div>
      </div>
    </section>
  );
}

// ============== FOOTER ==============
function PageFooter({ lang }) {
  return (
    <footer className="site-footer">
      <div className="container">
        <div className="foot-grid foot">
          <div className="foot-brand">
            <div className="name">Kenya Fujisaki</div>
            <p>{lang === "jp" ? "Product-minded Full-stack Engineer / PdM。SaaS・自動化・データ活用を中心に、事業の成長に伴走します。" : "Product-minded Full-stack Engineer / PdM. SaaS, automation, and data — partnering for growth."}</p>
          </div>
          <div>
            <h4>{lang === "jp" ? "セクション" : "Sections"}</h4>
            <ul>
              {(lang === "jp" ? ["プロジェクト","サービス","プロフィール","お問い合わせ"] : ["Projects","Services","Profile","Contact"]).map((t, i) => (
                <li key={i}><a href={`index.html#${["projects","services","profile","contact"][i]}`}>{t}</a></li>
              ))}
            </ul>
          </div>
          <div>
            <h4>{lang === "jp" ? "リンク" : "Elsewhere"}</h4>
            <ul>
              <li><a href="https://github.com/kenya6565" target="_blank" rel="noreferrer">GitHub</a></li>
              <li><a href="https://www.linkedin.com/in/kenya-fujisaki-93a4ba185/" target="_blank" rel="noreferrer">LinkedIn</a></li>
              <li><a href="https://www.wantedly.com/id/kenya_fujisaki" target="_blank" rel="noreferrer">Wantedly</a></li>
            </ul>
          </div>
          <div>
            <h4>{lang === "jp" ? "コンタクト" : "Contact"}</h4>
            <ul>
              <li><a href={`mailto:${CONTACT_CONFIG.email}`}>{CONTACT_CONFIG.email}</a></li>
              <li>{lang === "jp" ? "東京（リモート可）" : "Tokyo (Remote)"}</li>
            </ul>
          </div>
        </div>
        <div className="foot-bottom">
          <div>© 2026 Kenya Fujisaki. All rights reserved.</div>
        </div>
      </div>
    </footer>
  );
}

// ============== APP ==============
function App() {
  const [lang, setLang] = useState("jp");
  const [active, setActive] = useState("all");

  useEffect(() => {
    document.documentElement.setAttribute("data-lang", lang);
    document.documentElement.classList.add("proj-page");
    document.body.classList.add("proj-page");
  }, [lang]);

  // inject keyframe once
  useEffect(() => {
    if (!document.getElementById("proj-anim-style")) {
      const s = document.createElement("style");
      s.id = "proj-anim-style";
      s.textContent = "@keyframes fadeUp { from { opacity: 0; transform: translateY(14px); } to { opacity: 1; transform: translateY(0); } }";
      document.head.appendChild(s);
    }
  }, []);

  return (
    <div className="proj-page">
      <window.ParticlesBackground />
      <PageHeader lang={lang} setLang={setLang} />
      <main>
        <ProjectsHero lang={lang} />
        <Toolbar lang={lang} active={active} setActive={setActive} />
        <ProjectGrid lang={lang} active={active} />
      </main>
      <PageFooter lang={lang} />
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
