/* global React */
const { useState, useEffect, useRef, useMemo, Fragment } = React;

/* ============================================================
   ImagePlaceholder
   ============================================================ */
function ImagePlaceholder({ label, note, dim, className = "", style }) {
  return (
    <div className={`img-ph ${className}`} style={style}>
      <div className="ph-label">{label}</div>
      {note ? <div className="ph-note">{note}</div> : null}
      {dim ? <div className="ph-dim">{dim}</div> : null}
    </div>
  );
}

/* ============================================================
   Nav
   ============================================================ */
function useClock() {
  const [now, setNow] = useState(() => new Date());
  useEffect(() => {
    const t = setInterval(() => setNow(new Date()), 30000);
    return () => clearInterval(t);
  }, []);
  // Phnom Penh = UTC+7
  const fmt = new Intl.DateTimeFormat("en-GB", {
    hour: "2-digit",
    minute: "2-digit",
    hour12: false,
    timeZone: "Asia/Phnom_Penh",
  });
  return fmt.format(now);
}

function Nav({ route, setRoute, onOpenPalette, dark, onToggleTheme, onResetTheme, themeIsAuto }) {
  const time = useClock();
  const links = [
    { id: "home",    label: "Index" },
    { id: "ava",     label: "Work" },
    { id: "about",   label: "About" },
    { id: "contact", label: "Contact" },
  ];
  const themeTitle = themeIsAuto
    ? `Theme follows local sunrise / sunset (currently ${dark ? "night" : "day"}). Click to override.`
    : `Theme overridden to ${dark ? "dark" : "light"}. Double-click to restore auto sunrise / sunset.`;
  return (
    <header className="nav">
      <div className="shell-bleed nav-inner">
        <button className="brand" onClick={() => setRoute({ page: "home" })} aria-label="Olivier Ueno, home">
          <span className="mark">OU</span>
          <span className="brand-name">Olivier Ueno</span>
        </button>
        <nav className="nav-links">
          {links.map((l) => {
            const active =
              (l.id === "home" && route.page === "home") ||
              (l.id === "ava" && (route.page === "ava" || route.page === "stratco" || route.page === "hand")) ||
              l.id === route.page;
            return (
              <button
                key={l.id}
                className={`nav-link ${active ? "is-active" : ""}`}
                onClick={() => {
                  if (l.id === "ava") setRoute({ page: "home", scrollTo: "work" });
                  else setRoute({ page: l.id });
                }}
              >
                {l.label}
              </button>
            );
          })}
        </nav>
        <div className="nav-right">
          <span className="nav-time mono">
            <span className="status-dot" style={{ marginRight: 6, verticalAlign: "middle" }}></span>
            PNH {time}
          </span>
          {typeof onToggleTheme === "function" && (
            <button
              className="nav-theme"
              onClick={onToggleTheme}
              onDoubleClick={onResetTheme}
              title={themeTitle}
              aria-label={`Switch to ${dark ? "light" : "dark"} theme`}
            >
              <span className="nav-theme-glyph" aria-hidden="true">
                {dark ? (
                  /* moon */
                  <svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
                    <path d="M13.5 9.5A5.5 5.5 0 0 1 6.5 2.5a5.5 5.5 0 1 0 7 7Z" />
                  </svg>
                ) : (
                  /* sun */
                  <svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
                    <circle cx="8" cy="8" r="3" />
                    <path d="M8 1.5v1.5M8 13v1.5M1.5 8h1.5M13 8h1.5M3.4 3.4l1.1 1.1M11.5 11.5l1.1 1.1M3.4 12.6l1.1-1.1M11.5 4.5l1.1-1.1" />
                  </svg>
                )}
              </span>
              <span className="nav-theme-dot" data-auto={themeIsAuto ? "1" : "0"} />
            </button>
          )}
          <button className="nav-kbd-hint" onClick={onOpenPalette} title="Open quick nav (⌘K)">
            <span>Quick nav</span>
            <span className="kbd">⌘K</span>
          </button>
        </div>
      </div>
    </header>
  );
}

/* ============================================================
   Footer
   ============================================================ */
function Footer({ setRoute }) {
  return (
    <footer className="foot">
      <div className="shell-bleed">
        <div className="foot-inner">
          <div className="foot-col">
            <span className="eyebrow">Contact</span>
            <a className="foot-link" href="mailto:olivierueno@gmail.com">olivierueno@gmail.com</a>
            <a className="foot-link" href="https://www.linkedin.com/in/olivier-ueno/" target="_blank" rel="noopener">linkedin.com/in/olivier-ueno</a>
            <a className="foot-link" href="https://www.olivierueno.com" target="_blank" rel="noopener">olivierueno.com</a>
          </div>
          <div className="foot-col">
            <span className="eyebrow">Index</span>
            <button className="foot-link" onClick={() => setRoute({ page: "home" })} style={{ textAlign: "left" }}>Home</button>
            <button className="foot-link" onClick={() => setRoute({ page: "ava" })} style={{ textAlign: "left" }}>AVA Light</button>
            <button className="foot-link" onClick={() => setRoute({ page: "stratco" })} style={{ textAlign: "left" }}>Stratco Cambodia E&amp;D Department</button>
            <button className="foot-link" onClick={() => setRoute({ page: "hand" })} style={{ textAlign: "left" }}>Robotic Hand (R&amp;D)</button>
            <button className="foot-link" onClick={() => setRoute({ page: "about" })} style={{ textAlign: "left" }}>About</button>
          </div>
          <div className="foot-col">
            <span className="eyebrow">Location</span>
            <span className="foot-link" style={{ borderBottom: "none", cursor: "default" }}>Phnom Penh, Cambodia</span>
            <span className="foot-link" style={{ borderBottom: "none", cursor: "default" }}>Open to relocate: AU / SEA / Japan / USA</span>
          </div>
        </div>
        <div className="foot-meta">
          <span>© 2026 Olivier Ueno · Built in HTML, no tracking</span>
          <span>v1.0 · Last revised 26 May 2026</span>
        </div>
      </div>
    </footer>
  );
}

/* ============================================================
   Section title (used on inner pages)
   ============================================================ */
function SectionTitle({ num, children }) {
  return (
    <div className="section-title">
      <span>{children}</span>
      {num ? <span className="num">{num}</span> : null}
    </div>
  );
}

/* ============================================================
   Page head
   ============================================================ */
function PageHead({ eyebrow, title, meta }) {
  return (
    <div className="page-head">
      <div className="lead">
        <span className="eyebrow">{eyebrow}</span>
        <h1>{title}</h1>
      </div>
      <dl className="meta">
        {meta.map(([k, v]) => (
          <Fragment key={k}>
            <dt>{k}</dt>
            <dd>{v}</dd>
          </Fragment>
        ))}
      </dl>
    </div>
  );
}

/* ============================================================
   Project data: single source for cards + index
   ============================================================ */
const PROJECTS = [
  {
    id: "ava",
    no: "01",
    title: "AVA Light",
    sub: "OUDESIGNLAB, owned product",
    desc: "Upward-firing ceiling-bounce light, 1800K amber single-channel for circadian-supportive evening use. USB-C PD, passive thermal, fully analog. Designed, manufactured, and brought to market end to end.",
    role: "Designer / Engineer / Founder",
    year: "2021–2025",
    status: "Shipped",
    tags: ["Industrial design", "Analog electronics", "Thermal", "DFM"],
    thumbSrc: "assets/ava-thumb.jpg",
    placeholderNote: "AVA light, three-quarter product shot on neutral seamless background",
  },
  {
    id: "stratco",
    no: "02",
    title: "Stratco Cambodia: Engineering & Design Department",
    sub: "Function-building case study",
    desc: "Formalised a limited in-house engineering function for the Cambodia operation. 21-project portfolio, 5 products to production in 4 months.",
    role: "Design & Engineering Manager",
    year: "2026",
    status: "Completed",
    tags: ["Leadership", "Process design", "DFM", "Power Automate"],
    thumbSrc: "assets/stratco-dept-banner.jpg",
    placeholderNote: "Workflow diagram: intake to tracker to manufacturing standards",
  },
  {
    id: "hand",
    no: "03",
    title: "Robotic Hand",
    sub: "Personal R&D, 2020 to present",
    desc: "Tendon-driven robotic hand mechanism, seven mechanical iterations. Honours pivot to a wearable electro-tactile glove for blind navigation (Project Vision Sixth Sense, First Class Honours, RMIT).",
    role: "Researcher / Engineer / Designer",
    year: "2020–present",
    status: "R&D",
    tags: ["Mechanism", "Electronics", "Haptics", "Design research"],
    thumbSrc: "assets/hand-thumb.jpg",
    placeholderNote: "Hand prototype lineup or honours-glove render",
  },
];

/* ============================================================
   Project index (3 thumbnail styles)
   ============================================================ */
function ProjectIndex({ style, setRoute }) {
  if (style === "image") {
    return (
      <div className="proj-grid--image">
        {PROJECTS.map((p) => (
          <button
            key={p.id}
            className="proj-card--image"
            onClick={() => setRoute({ page: p.id })}
            aria-label={`Open ${p.title}`}
          >
            <div
              className="thumb"
              style={p.thumbSrc ? { backgroundImage: `url(${p.thumbSrc})` } : undefined}
            >
              <span className="num">{p.no} / 03</span>
              <span className="badge">{p.status}</span>
              {!p.thumbSrc && (
                <ImagePlaceholder label={p.id.toUpperCase()} note={p.placeholderNote} style={{ position: "absolute", inset: 0, border: 0, borderRadius: 0, background: "transparent", minHeight: 0 }} />
              )}
            </div>
            <div className="meta">
              <span>{p.year}</span>
              <span>{p.role}</span>
            </div>
            <h3>{p.title}</h3>
            <p className="desc">{p.desc}</p>
          </button>
        ))}
      </div>
    );
  }
  if (style === "number") {
    return (
      <div className="proj-grid--number">
        {PROJECTS.map((p) => (
          <button key={p.id} className="proj-card--number" onClick={() => setRoute({ page: p.id })}>
            <div className="num">{p.no}</div>
            <div>
              <h3>{p.title}</h3>
              <div className="desc fg-second" style={{ fontSize: "0.9rem", marginTop: 6, maxWidth: "50ch" }}>{p.desc}</div>
            </div>
            <div className="tags">
              {p.tags.slice(0, 3).map((t) => (
                <span key={t} className="tag">{t}</span>
              ))}
            </div>
            <div className="meta-right">
              <span className="year">{p.year}</span>
              <span>{p.status} →</span>
            </div>
          </button>
        ))}
      </div>
    );
  }
  // text / tabular register
  return (
    <div className="proj-grid--text">
      <div className="row header">
        <span>№</span>
        <span>Project</span>
        <span className="role-cell">Role</span>
        <span>Year</span>
        <span className="status-cell">Status</span>
        <span></span>
      </div>
      {PROJECTS.map((p) => (
        <button
          key={p.id}
          className="row"
          onClick={() => setRoute({ page: p.id })}
          style={{ textAlign: "left" }}
        >
          <span className="fg-faint">{p.no}</span>
          <span className="title-cell">{p.title}<br/><span className="fg-muted" style={{ fontFamily: "var(--u-font-mono)", fontSize: 11, fontWeight: 400 }}>{p.sub}</span></span>
          <span className="role-cell fg-second">{p.role}</span>
          <span className="fg-second">{p.year}</span>
          <span className="status-cell fg-second">{p.status}</span>
          <span className="arrow-cell">→</span>
        </button>
      ))}
    </div>
  );
}

/* ============================================================
   Export to window so other JSX files can use them
   ============================================================ */
Object.assign(window, {
  ImagePlaceholder,
  Nav,
  Footer,
  SectionTitle,
  PageHead,
  ProjectIndex,
  PROJECTS,
  useClock,
});
