/* global React, Reveal, Icon, WorksData */
// Portfolio — reads from WorksData, supports image/video uploads, clickable swap.

const { useState: useSP, useEffect: useEP, useRef: useRP } = React;

/* ---------- Mock screens (used when no media uploaded) ---------- */

function MockLemonTablet() {
  return (
    <div style={mockBase("light")}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <div style={{ fontFamily: "var(--serif)", fontSize: 13, color: "var(--ink)" }}>Lemon</div>
        <div style={{ display: "flex", gap: 6 }}>
          <div style={{ width: 24, height: 6, borderRadius: 3, background: "rgba(0,0,0,0.08)" }} />
          <div style={{ width: 6, height: 6, borderRadius: 3, background: "var(--gold)" }} />
        </div>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8, flex: 1 }}>
        {[
          { p: "VILLA AKAMAS", n: "M. Cohen", t: "11:00" },
          { p: "MARINA #14", n: "S. Andreou", t: "13:30" },
          { p: "SEAFRONT 7B", n: "A. Petrov", t: "15:00" },
          { p: "OLD TOWN A1", n: "L. Demetriou", t: "16:00" },
        ].map((c, i) => (
          <div key={i} style={mockCard()}>
            <div style={{ display: "flex", justifyContent: "space-between" }}>
              <span style={{ fontSize: 8, letterSpacing: "0.12em", color: "var(--ink-3)" }}>{c.p}</span>
              <span style={{ fontSize: 8, color: "var(--gold-dark)" }}>{c.t}</span>
            </div>
            <div style={{ fontFamily: "var(--serif)", fontSize: 12, color: "var(--ink)" }}>{c.n}</div>
            <div style={{ display: "flex", gap: 10, alignItems: "center" }}>
              <span style={{ width: 8, height: 8, borderRadius: "50%", background: "var(--gold)" }} />
              <div style={{ flex: 1, height: 3, background: "rgba(0,0,0,0.06)", borderRadius: 2 }} />
            </div>
          </div>
        ))}
      </div>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <span style={mockPill()}>Today · 4 jobs</span>
        <span style={{ fontSize: 8, color: "var(--ink-3)", letterSpacing: "0.14em" }}>3 ACTIVE</span>
      </div>
    </div>
  );
}
function MockLemonPhone() {
  return (
    <div style={mockBase("light", 28)}>
      <div style={{ fontSize: 7, letterSpacing: "0.16em", color: "var(--gold-dark)", fontWeight: 500 }}>NEXT JOB</div>
      <div style={{ fontFamily: "var(--serif)", fontSize: 15, color: "var(--ink)", marginTop: 2, lineHeight: 1.1 }}>Villa Akamas</div>
      <div style={{ fontSize: 8, color: "var(--ink-3)", marginTop: 4 }}>11:00 · Maria</div>
      <div style={{ flex: 1, marginTop: 12, display: "flex", flexDirection: "column", gap: 7 }}>
        {["Linen change", "Pool deck", "Welcome pack"].map((s, i) => (
          <div key={i} style={{ display: "flex", gap: 8, alignItems: "center", fontSize: 9, color: "var(--ink-2)" }}>
            <span style={{ width: 10, height: 10, border: "1px solid rgba(0,0,0,0.18)", borderRadius: "50%", background: i === 0 ? "var(--gold)" : "transparent" }} />
            {s}
          </div>
        ))}
      </div>
      <div style={{ height: 26, background: "var(--ink)", borderRadius: 8, display: "flex", alignItems: "center", justifyContent: "center", color: "#fff", fontSize: 8, letterSpacing: "0.14em" }}>START</div>
    </div>
  );
}

function MockPhotoWallTablet() {
  return (
    <div style={mockBase("dark")}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <div style={{ fontFamily: "var(--serif)", fontSize: 13, color: "#fff" }}>PhotoWall — V & K</div>
        <span style={{ ...mockPill(), background: "rgba(200,169,110,0.22)", color: "var(--gold)" }}>LIVE</span>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 6, flex: 1 }}>
        {Array.from({ length: 16 }).map((_, i) => {
          const tones = [
            "linear-gradient(135deg,#2a2a2a,#1a1a1a)",
            "linear-gradient(135deg,#3b322a,#1f1a14)",
            "linear-gradient(135deg,#1f2a35,#13191f)",
            "linear-gradient(135deg,#2c2419,#1c1611)",
          ];
          return (
            <div key={i} style={{ aspectRatio: "1/1", background: tones[i % tones.length], borderRadius: 5, position: "relative" }}>
              {i === 2 && <span style={{ position: "absolute", top: 3, right: 3, fontSize: 6, color: "var(--gold)", letterSpacing: "0.1em" }}>AI</span>}
            </div>
          );
        })}
      </div>
      <div style={{ display: "flex", justifyContent: "space-between", fontSize: 8, color: "rgba(255,255,255,0.5)", letterSpacing: "0.14em" }}>
        <span>134 PHOTOS</span>
        <span>4 PENDING</span>
      </div>
    </div>
  );
}
function MockPhotoWallPhone() {
  return (
    <div style={mockBase("dark", 28)}>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 5, flex: 1 }}>
        {Array.from({ length: 8 }).map((_, i) => (
          <div key={i} style={{ aspectRatio: "1/1", background: "linear-gradient(135deg,#3b322a,#1a1611)", borderRadius: 4 }} />
        ))}
      </div>
      <div style={{ marginTop: 8, height: 30, background: "var(--gold)", borderRadius: 10, display: "flex", alignItems: "center", justifyContent: "center", color: "#fff", fontSize: 9, letterSpacing: "0.14em", fontWeight: 500 }}>＋ ADD PHOTO</div>
    </div>
  );
}

function MockPitsillisTablet() {
  return (
    <div style={mockBase("light")}>
      <div style={{ display: "flex", justifyContent: "space-between" }}>
        <div style={{ fontFamily: "var(--serif)", fontSize: 16, color: "var(--ink)" }}>Pitsillis Menu</div>
        <div style={{ fontSize: 8, color: "var(--ink-3)", letterSpacing: "0.14em" }}>SPRING · 2026</div>
      </div>
      <div style={{ display: "flex", gap: 10, flex: 1 }}>
        <div style={{ flex: 1, display: "flex", flexDirection: "column", gap: 7 }}>
          {[
            { n: "Souvla", p: "€18" },
            { n: "Halloumi grilled", p: "€7" },
            { n: "Sheftalia", p: "€14" },
            { n: "Lamb kleftiko", p: "€26" },
            { n: "Village salad", p: "€9" },
          ].map((d, i) => (
            <div key={i} style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", borderBottom: "1px dotted rgba(0,0,0,0.12)", paddingBottom: 4 }}>
              <span style={{ fontFamily: "var(--serif)", fontSize: 11, color: "var(--ink)" }}>{d.n}</span>
              <span style={{ fontSize: 9, color: "var(--gold-dark)", fontWeight: 500 }}>{d.p}</span>
            </div>
          ))}
        </div>
        <div style={{ width: 92, background: "linear-gradient(160deg,#e8dec8,#c9b78a)", borderRadius: 8, position: "relative", overflow: "hidden" }}>
          <div style={{ position: "absolute", inset: 0, background: "radial-gradient(circle at 30% 30%, rgba(255,255,255,0.3), transparent 60%)" }} />
        </div>
      </div>
    </div>
  );
}
function MockPitsillisPhone() {
  return (
    <div style={mockBase("light", 28)}>
      <div style={{ fontFamily: "var(--serif)", fontSize: 13, color: "var(--ink)" }}>MENU</div>
      <div style={{ flex: 1, display: "flex", flexDirection: "column", gap: 9 }}>
        {[
          { n: "Souvla", p: "€18" },
          { n: "Halloumi", p: "€7" },
          { n: "Sheftalia", p: "€14" },
          { n: "Kleftiko", p: "€26" },
        ].map((d, i) => (
          <div key={i} style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", borderBottom: "1px dotted rgba(0,0,0,0.12)", paddingBottom: 4 }}>
            <span style={{ fontFamily: "var(--serif)", fontSize: 11, color: "var(--ink)" }}>{d.n}</span>
            <span style={{ fontSize: 8, color: "var(--gold-dark)" }}>{d.p}</span>
          </div>
        ))}
      </div>
      <div style={{ fontSize: 8, color: "var(--ink-3)", letterSpacing: "0.14em", textAlign: "center" }}>PITSILLIS CATERING</div>
    </div>
  );
}

function MockGenericTablet({ name }) {
  return (
    <div style={mockBase("light")}>
      <div style={{ fontFamily: "var(--serif)", fontSize: 16, color: "var(--ink)" }}>{name || "Project"}</div>
      <div style={{ flex: 1, display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 8 }}>
        {Array.from({ length: 6 }).map((_, i) => (
          <div key={i} style={{ background: "#fff", border: "1px solid var(--border)", borderRadius: 8 }} />
        ))}
      </div>
      <div style={{ display: "flex", justifyContent: "space-between", fontSize: 8, color: "var(--ink-3)", letterSpacing: "0.14em" }}>
        <span>PROJECT VIEW</span>
        <span>WORKS.CY</span>
      </div>
    </div>
  );
}
function MockGenericPhone({ name }) {
  return (
    <div style={mockBase("light", 28)}>
      <div style={{ fontFamily: "var(--serif)", fontSize: 13, color: "var(--ink)" }}>{name || "Project"}</div>
      <div style={{ flex: 1, display: "flex", flexDirection: "column", gap: 7, marginTop: 6 }}>
        {Array.from({ length: 4 }).map((_, i) => (
          <div key={i} style={{ height: 30, background: "#fff", border: "1px solid var(--border)", borderRadius: 7 }} />
        ))}
      </div>
    </div>
  );
}

function mockBase(theme, pad = 18) {
  return {
    width: "100%",
    height: "100%",
    display: "flex",
    flexDirection: "column",
    padding: pad,
    gap: 10,
    background: theme === "dark" ? "#0f0f0f" : "#fafaf7",
    color: theme === "dark" ? "#fff" : "var(--ink)",
  };
}
function mockCard() {
  return {
    background: "#fff",
    border: "1px solid var(--border)",
    borderRadius: 10,
    padding: 12,
    display: "flex",
    flexDirection: "column",
    gap: 7,
  };
}
function mockPill() {
  return {
    display: "inline-block",
    fontSize: 7,
    letterSpacing: "0.16em",
    textTransform: "uppercase",
    padding: "3px 8px",
    borderRadius: 999,
    background: "var(--gold-tint)",
    color: "var(--gold-dark)",
    fontWeight: 500,
  };
}

const MOCKS = {
  lemon: { tablet: <MockLemonTablet />, phone: <MockLemonPhone /> },
  photowall: { tablet: <MockPhotoWallTablet />, phone: <MockPhotoWallPhone /> },
  pitsillis: { tablet: <MockPitsillisTablet />, phone: <MockPitsillisPhone /> },
};

function sniffType(src) {
  if (!src) return "image";
  if (src.startsWith("data:video")) return "video";
  if (/\.(mp4|webm|mov|ogg|ogv)(\?|$)/i.test(src)) return "video";
  return "image";
}

function renderScreen(media, mockKind, slot, projectName) {
  if (media && media.src) {
    const t = media.type === "video" || sniffType(media.src) === "video" ? "video" : "image";
    if (t === "video") return <video className="dev-media" src={media.src} autoPlay muted loop playsInline />;
    return <img className="dev-media" src={media.src} alt="" />;
  }
  if (mockKind && MOCKS[mockKind]) return MOCKS[mockKind][slot];
  return slot === "tablet" ? <MockGenericTablet name={projectName} /> : <MockGenericPhone name={projectName} />;
}

/* ---------- Device frame with swap state ---------- */

function DeviceMockup({ project }) {
  const [state, setState] = useSP("a"); // 'a' = tablet leads, 'b' = phone leads
  const toggle = () => setState(state === "a" ? "b" : "a");
  return (
    <div className={"pf-device state-" + state}>
      <div className="dev dev-tablet" onClick={toggle} role="button" aria-label="Toggle device view">
        <div className="dev-screen">{renderScreen(project.tablet, project.mock, "tablet", project.name)}</div>
      </div>
      <div className="dev dev-phone" onClick={toggle} role="button" aria-label="Toggle device view">
        <div className="phone-notch" />
        <div className="dev-screen">{renderScreen(project.phone, project.mock, "phone", project.name)}</div>
      </div>
    </div>
  );
}

/* ---------- Row + Section ---------- */

function PortfolioRow({ project, reverse }) {
  return (
    <div className={"portfolio-row" + (reverse ? " reverse" : "")}>
      <Reveal className="pf-text" dir={reverse ? "right" : "left"}>
        <div className="eyebrow">{project.eyebrow}</div>
        <h3 className="serif">{project.name}</h3>
        <div className="client">
          Client: <span style={{ color: "var(--ink)" }}>{project.client}</span>
        </div>
        <p className="desc">{project.desc}</p>
      </Reveal>
      <Reveal dir={reverse ? "left" : "right"} delay={120}>
        <DeviceMockup project={project} />
      </Reveal>
    </div>
  );
}

function Portfolio() {
  const [data, setData] = useSP(() => WorksData.load());
  useEP(() => {
    const onChange = () => setData(WorksData.load());
    window.addEventListener("storage", onChange);
    return () => window.removeEventListener("storage", onChange);
  }, []);
  const projects = data.projects || [];
  const count = projects.length;
  const pad = (n) => String(n).padStart(3, "0");
  return (
    <section className="pad portfolio" id="work">
      <div className="shell">
        <Reveal className="portfolio-head">
          <div className="portfolio-rule">
            <span className="ph-rule" />
            <span className="ph-rule-tag">Vol. III · 2022 — 2026</span>
            <span className="ph-rule" />
          </div>
          <div className="portfolio-eyebrow">Selected Work</div>
          <h2 className="portfolio-title">
            <span className="pt-line">Products</span>
            <span className="pt-line"><em>we&apos;ve shipped.</em></span>
          </h2>
          <div className="portfolio-meta">
            <div className="pm-cell">
              <span className="pm-num">{pad(count)}</span>
              <span className="pm-label">Products</span>
            </div>
            <div className="pm-divider" />
            <div className="pm-cell">
              <span className="pm-num">100<small>%</small></span>
              <span className="pm-label">In production</span>
            </div>
            <div className="pm-divider" />
            <div className="pm-cell">
              <span className="pm-num">0</span>
              <span className="pm-label">Launch-day bugs</span>
            </div>
          </div>
          <div className="portfolio-sub">
            A small portfolio. Every one in production. Every one still running.
          </div>
        </Reveal>
        {projects.map((p, i) => (
          <PortfolioRow key={p.id} project={p} reverse={i % 2 === 1} />
        ))}
      </div>
    </section>
  );
}

Object.assign(window, { Portfolio });
