/* global React, Icon, SectionHeader, Reveal */
const { useState, useMemo } = React;

// ============================================================
// Mock visuals — CSS-drawn product mockups suggesting each project.
// Treat these as visual placeholders for real screenshots.
// ============================================================

function MockChrome({ title, children, theme = "light" }) {
  return (
    <div className="mock-window">
      <div className="mock-titlebar">
        <span className="mock-dot mock-dot--r" />
        <span className="mock-dot mock-dot--y" />
        <span className="mock-dot mock-dot--g" />
      </div>
      <div className="mock-content">{children}</div>
    </div>
  );
}

function KPIRow() {
  return (
    <div className="mock-row">
      {[78, 42, 65].map((p, i) => (
        <div className="mock-kpi" key={i}>
          <div className="mock-kpi-lbl">KPI {i + 1}</div>
          <div className="mock-kpi-num">{(p * 10).toLocaleString()}</div>
          <div className="mock-kpi-bar"><div style={{ width: p + "%" }} /></div>
        </div>
      ))}
    </div>
  );
}

function BarsChart({ count = 10, heights }) {
  const hs = heights || Array.from({ length: count }, (_, i) =>
    35 + Math.round(45 * Math.sin(i * 1.1) + 20 * Math.cos(i * 0.7) + Math.random() * 8)
  );
  return (
    <div className="mock-chart">
      {hs.map((h, i) => (
        <div className="mock-bar" key={i} style={{ height: Math.max(15, h) + "%" }} />
      ))}
    </div>
  );
}

function LineChart() {
  // simple area chart
  return (
    <div className="mock-chart" style={{ padding: 10 }}>
      <svg viewBox="0 0 100 40" preserveAspectRatio="none" className="mock-line-svg">
        <defs>
          <linearGradient id="larea" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="#02A0C1" stopOpacity="0.35" />
            <stop offset="100%" stopColor="#02A0C1" stopOpacity="0" />
          </linearGradient>
        </defs>
        <path d="M0 32 L10 26 L20 28 L30 18 L40 22 L50 14 L60 10 L70 16 L80 8 L90 12 L100 6 L100 40 L0 40 Z" fill="url(#larea)" />
        <path d="M0 32 L10 26 L20 28 L30 18 L40 22 L50 14 L60 10 L70 16 L80 8 L90 12 L100 6" stroke="#02A0C1" strokeWidth="1.2" fill="none" strokeLinecap="round" strokeLinejoin="round" />
        <path d="M0 36 L10 32 L20 34 L30 28 L40 30 L50 24 L60 22 L70 26 L80 20 L90 22 L100 18" stroke="#3581E1" strokeWidth="1" strokeDasharray="2 2" fill="none" strokeLinecap="round" />
      </svg>
    </div>
  );
}

function TableMock({ rows = 4 }) {
  return (
    <div className="mock-kpi" style={{ flex: 2 }}>
      {Array.from({ length: rows }).map((_, i) => (
        <div className="mock-table-row" key={i}>
          <div className="mock-cell x1" style={{ width: 8 }} />
          <div className="mock-cell x3" />
          <div className={`mock-cell x1 ${i === 0 ? "fill" : ""}`} />
          <div className="mock-cell x1" />
        </div>
      ))}
    </div>
  );
}

function PieMock({ rows = 4 }) {
  const legend = [
    { c: "var(--brand-primary)",       l: "Primary" },
    { c: "var(--brand-secondary)",     l: "Secondary" },
    { c: "var(--brand-accent-green)",  l: "Tertiary" },
    { c: "var(--brand-soft-teal)",     l: "Other" },
  ];
  return (
    <div className="mock-kpi" style={{ flexDirection: "row", alignItems: "center", gap: 12, flex: 2 }}>
      <div className="mock-pie" />
      <div style={{ display: "flex", flexDirection: "column", gap: 4, flex: 1 }}>
        {legend.slice(0, rows).map((l, i) => (
          <div className="mock-stack-row" key={i}>
            <span className="swatch" style={{ background: l.c }} />
            <span>{l.l}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

// ============================================================
// Project mock dispatcher
// ============================================================
function ProjectMock({ kind }) {
  if (kind === "powerbi") {
    return (
      <MockChrome>
        <KPIRow />
        <div className="mock-row" style={{ flex: 1 }}>
          <BarsChart count={12} />
          <PieMock />
        </div>
      </MockChrome>
    );
  }
  if (kind === "tableau") {
    return (
      <MockChrome>
        <KPIRow />
        <div className="mock-row" style={{ flex: 1 }}>
          <LineChart />
          <TableMock rows={5} />
        </div>
      </MockChrome>
    );
  }
  if (kind === "erp") {
    return (
      <MockChrome>
        <div className="mock-row">
          <div className="mock-kpi" style={{ flex: 1 }}>
            <div className="mock-kpi-lbl">Modules</div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 4, marginTop: 4 }}>
              {["FIN", "SCM", "PRJ", "HCM"].map(m => (
                <div key={m} style={{ background: "var(--brand-soft-blue)", color: "var(--brand-primary)", borderRadius: 4, padding: "3px 4px", fontSize: 8, fontWeight: 800, textAlign: "center", letterSpacing: ".04em" }}>{m}</div>
              ))}
            </div>
          </div>
          <div className="mock-kpi" style={{ flex: 1 }}>
            <div className="mock-kpi-lbl">Status</div>
            <div className="mock-kpi-num" style={{ color: "var(--brand-primary)" }}>Live</div>
            <div className="mock-kpi-bar"><div style={{ width: "92%" }} /></div>
          </div>
        </div>
        <TableMock rows={6} />
      </MockChrome>
    );
  }
  if (kind === "phone") {
    return (
      <>
        <div className="mock-phone">
          <div className="mock-phone-screen">
            <div className="mock-phone-header">
              <div className="mock-phone-dot" />
              <div className="mock-phone-title" />
            </div>
            <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
              {[88, 64, 52].map((p, i) => (
                <div key={i} className="mock-kpi" style={{ padding: 5, gap: 2 }}>
                  <div className="mock-kpi-lbl" style={{ fontSize: 6 }}>Equipment {i + 1}</div>
                  <div className="mock-kpi-bar"><div style={{ width: p + "%" }} /></div>
                </div>
              ))}
            </div>
            <div style={{ marginTop: "auto", display: "flex", gap: 3 }}>
              <div style={{ flex: 1, height: 14, borderRadius: 6, background: "var(--brand-primary)" }} />
              <div style={{ width: 14, height: 14, borderRadius: 6, background: "var(--neutral-light)" }} />
            </div>
          </div>
        </div>
      </>
    );
  }
  if (kind === "flow") {
    // Workflow-style visual for FUMS
    return (
      <MockChrome>
        <div style={{ flex: 1, display: "flex", flexDirection: "column", gap: 6, padding: "4px 2px" }}>
          {["Source", "Validate", "Route", "Deliver"].map((s, i) => (
            <div key={s} style={{ display: "flex", alignItems: "center", gap: 6 }}>
              <div style={{ width: 22, height: 22, borderRadius: 6, background: i === 1 ? "var(--brand-accent-green)" : "var(--brand-soft-blue)", color: i === 1 ? "#1F1F1F" : "var(--brand-primary)", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 8, fontWeight: 800 }}>{i + 1}</div>
              <div style={{ flex: 1, height: 18, background: "var(--neutral-page)", borderRadius: 6, display: "flex", alignItems: "center", paddingLeft: 8 }}>
                <div style={{ height: 5, width: "50%", background: "var(--brand-primary)", borderRadius: 2, opacity: i === 0 ? 1 : 0.4 }} />
              </div>
              <div style={{ fontSize: 8, fontWeight: 800, color: "var(--text-muted)" }}>{s}</div>
            </div>
          ))}
        </div>
        <BarsChart count={8} />
      </MockChrome>
    );
  }
  // default
  return (
    <MockChrome>
      <KPIRow />
      <BarsChart count={9} />
    </MockChrome>
  );
}

// ============================================================
// Project data
// ============================================================
const PROJECTS = [
  {
    id: "p1",
    featured: true,
    kind: "powerbi",
    cat: "BI / Power BI",
    label: "Power BI",
    title: "Enterprise Power BI Dashboard",
    desc: "End-to-end logistics analytics dashboard with multi-source modeling, custom DAX, and an executive narrative view used across plant operations.",
    role: "Data Visualization Specialist",
    impact: "Cut weekly reporting cycle from 3 days → 4 hours",
    stack: ["Power BI", "DAX", "SQL", "Power Query"],
    tag: "Featured",
  },
  {
    id: "p2",
    kind: "flow",
    cat: "Systems",
    label: "Web app",
    title: "FUMS Transport",
    desc: "Fuel Supply Integrated System for Adaro Group — managing fuel movement, validation, and reconciliation across operational sites.",
    role: "Product Owner",
    impact: "Single source of fuel truth across sites",
    stack: ["Web", "Workflow", "SQL"],
  },
  {
    id: "p3",
    kind: "erp",
    cat: "ERP",
    label: "ERP",
    title: "Ellipse 9 ERP",
    desc: "Asset-management ERP implementation — module rollout, business process redesign, and adoption support for heavy operations.",
    role: "Business Analyst",
    impact: "Enterprise-wide asset management live",
    stack: ["Ellipse 9", "Asset mgmt", "BPM"],
  },
  {
    id: "p4",
    kind: "erp",
    cat: "ERP",
    label: "SAP",
    title: "SAP S/4HANA ERP",
    desc: "Enterprise ERP transformation — supporting requirements, process design, and operational reporting on the new platform.",
    role: "Business Analyst",
    impact: "Real-time finance + supply visibility",
    stack: ["SAP S/4HANA", "Fiori", "BPM"],
  },
  {
    id: "p5",
    kind: "phone",
    cat: "Systems",
    label: "Product",
    title: "Fosto Oli",
    desc: "Oil Management System for Pamapersada Nusantara — tracking oil usage, sampling, and lifecycle across heavy equipment fleets.",
    role: "Project Manager",
    impact: "Standardized oil program across fleet",
    stack: ["Mobile", "Web", "SQL"],
  },
  {
    id: "p6",
    kind: "tableau",
    cat: "BI / Tableau",
    label: "Tableau",
    title: "Tableau Analytics Dashboard",
    desc: "Supply Management analytics dashboard — supplier performance, lead times, and spend visibility for procurement leadership.",
    role: "Data Visualization Specialist",
    impact: "Faster supplier &amp; spend decisions",
    stack: ["Tableau", "SQL", "ETL"],
  },
  {
    id: "p7",
    kind: "default",
    cat: "Systems",
    label: "Web app",
    title: "Use It",
    desc: "Used Equipment Integrated System — internal marketplace and lifecycle platform for retired and reusable heavy equipment.",
    role: "Product Manager",
    impact: "Recovered value from idle equipment",
    stack: ["Web", "SQL", "Inventory"],
  },
  {
    id: "p8",
    kind: "erp",
    cat: "ERP",
    label: "Mini ERP",
    title: "Mini ERP",
    desc: "Lightweight internal ERP focused on supply, procurement, and operational reporting for a single business unit.",
    role: "Project Manager",
    impact: "Replaced 6 disconnected spreadsheets",
    stack: ["Web", "SQL", "Workflow"],
  },
];

const FILTERS = [
  { id: "all",     label: "All projects" },
  { id: "BI / Power BI", label: "Power BI" },
  { id: "BI / Tableau",  label: "Tableau" },
  { id: "ERP",     label: "ERP" },
  { id: "Systems", label: "Systems &amp; Products" },
];

function Projects() {
  const [active, setActive] = useState("all");
  const list = useMemo(() => {
    if (active === "all") return PROJECTS;
    return PROJECTS.filter(p => p.cat === active);
  }, [active]);

  return (
    <section id="projects" className="section projects">
      <div className="container">
        <Reveal>
          <SectionHeader
            eyebrow="Featured projects"
            eyebrowIcon="folder-open"
            title='Eight years of <span class="grad">shipping&nbsp;systems.</span>'
            subtitle="Enterprise dashboards, ERPs, and internal products — built across mining, logistics, and supply chain for groups like Adaro, ITM and PAMA."
          />
        </Reveal>

        <Reveal delay={80}>
          <div className="projects-toolbar">
            <div className="filter-pills" role="tablist">
              {FILTERS.map(f => (
                <button
                  key={f.id}
                  className={`filter-pill ${active === f.id ? "is-active" : ""}`}
                  onClick={() => setActive(f.id)}
                  dangerouslySetInnerHTML={{ __html: f.label }}
                />
              ))}
            </div>
            <span className="pill pill--white">
              <Icon name="folder" size={12} />
              {list.length} project{list.length === 1 ? "" : "s"} shown
            </span>
          </div>
        </Reveal>

        <div className="projects-grid">
          {list.map((p, i) => (
            <Reveal key={p.id} delay={(i % 4) * 60}>
              <a className={`project-card ${p.featured ? "is-featured" : ""}`} href="#">
                <div className="project-mock">
                  <div className="project-mock-pill">
                    <Icon name="layout-dashboard" size={11} />
                    {p.label}
                  </div>
                  {p.tag && <div className="project-mock-tag">{p.tag}</div>}
                  <div className="mock-scene">
                    <ProjectMock kind={p.kind} />
                  </div>
                </div>
                <div className="project-body">
                  <div className="project-role">{p.role}</div>
                  <h3 className="project-title" dangerouslySetInnerHTML={{ __html: p.title }} />
                  <p className="project-desc">{p.desc}</p>
                  <div className="project-impact">
                    <Icon name="trending-up" size={14} />
                    <span dangerouslySetInnerHTML={{ __html: p.impact }} />
                  </div>
                  <div className="project-stack">
                    {p.stack.map(s => <span className="pill" key={s}>{s}</span>)}
                  </div>
                  <span className="project-cta">
                    View case study <Icon name="arrow-right" size={14} />
                  </span>
                </div>
              </a>
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
}

window.Projects = Projects;
