/* global React */
/* ============================================================
   .pics — shared bits (atoms used across screens)
   Exports to window: PicsBackdrop, PicsNav, PicsFooter,
   ProgressBar, PhotoTile, PhotoPlaceholder, AxisRow,
   SwatchAxis, StarRating, IconBadge, MetaStrip, Icon
   ============================================================ */

const { useState, useEffect, useMemo } = React;

/* ---- icons (Lucide-style monochrome strokes, currentColor) ---- */
function Icon({ name, size = 16, strokeWidth = 1.6 }) {
  const s = strokeWidth;
  const common = {
    width: size, height: size, viewBox: "0 0 24 24",
    fill: "none", stroke: "currentColor", strokeWidth: s,
    strokeLinecap: "round", strokeLinejoin: "round",
    "aria-hidden": "true"
  };
  const paths = {
    "chevron-down": <polyline points="6 9 12 15 18 9" />,
    "chevron-right": <polyline points="9 6 15 12 9 18" />,
    "arrow-right": <><line x1="5" y1="12" x2="19" y2="12" /><polyline points="12 5 19 12 12 19" /></>,
    "camera": <><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/><circle cx="12" cy="13" r="4"/></>,
    "sparkles": <><path d="M12 3v3M12 18v3M3 12h3M18 12h3M5 5l2 2M17 17l2 2M5 19l2-2M17 7l2-2"/><circle cx="12" cy="12" r="2.5"/></>,
    "check": <polyline points="20 6 9 17 4 12" />,
    "x": <><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></>,
    "image": <><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="9" cy="9" r="2"/><path d="m21 15-5-5L5 21"/></>,
    "user": <><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></>,
    "download": <><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></>,
    "share": <><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><line x1="8.59" y1="13.51" x2="15.42" y2="17.49"/><line x1="15.41" y1="6.51" x2="8.59" y2="10.49"/></>,
    "settings": <><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></>,
    "refresh": <><polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></>,
    "play": <polygon points="5 3 19 12 5 21 5 3" />,
    "lock": <><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></>,
    "shield": <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>,
    "eye-off": <><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"/><line x1="1" y1="1" x2="23" y2="23"/></>,
    "plus": <><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></>,
    "minus": <line x1="5" y1="12" x2="19" y2="12"/>,
    "menu": <><line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="18" x2="21" y2="18"/></>,
    "star": <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/>,
    "circle-dot": <><circle cx="12" cy="12" r="10"/><circle cx="12" cy="12" r="3"/></>,
    "info": <><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></>,
    "credit-card": <><rect x="2" y="5" width="20" height="14" rx="2" ry="2"/><line x1="2" y1="10" x2="22" y2="10"/></>,
    "google": <path d="M21.35 11.1H12v3.9h5.35c-.25 1.4-1.7 4.1-5.35 4.1-3.22 0-5.85-2.67-5.85-5.95s2.63-5.95 5.85-5.95c1.83 0 3.06.78 3.76 1.45l2.56-2.46C16.85 4.92 14.7 4 12 4 6.96 4 2.88 8.08 2.88 13.15S6.96 22.3 12 22.3c6.92 0 9.5-4.86 9.5-7.31 0-.5-.05-.95-.15-1.4z" strokeWidth="0" fill="currentColor" />
  };
  return <svg {...common}>{paths[name] || null}</svg>;
}

/* ---- Backdrop: stage + grain + sheen + optional effect ---- */
function PicsBackdrop({ effect }) {
  return (
    <>
      <div className="pics-bg-stage"></div>
      <div className="pics-bg-grain"></div>
      {effect === "circuit" && (
        <div className="pics-bg-circuit">
          <svg viewBox="0 0 1200 800" preserveAspectRatio="xMidYMid slice">
            <path d="M50 100 L300 100 L300 250 L600 250 L600 400 L900 400" />
            <path d="M100 600 L400 600 L400 450 L750 450 L750 600 L1100 600" />
            <path d="M0 350 L200 350 L200 200 L500 200" />
            <circle cx="300" cy="100" r="2.5"/>
            <circle cx="600" cy="250" r="2.5"/>
            <circle cx="900" cy="400" r="2.5"/>
            <circle cx="400" cy="600" r="2.5"/>
            <circle cx="750" cy="450" r="2.5"/>
          </svg>
        </div>
      )}
      {effect === "aura" && (
        <div className="pics-bg-aura">
          <span className="blob b1"></span>
          <span className="blob b2"></span>
          <span className="blob b3"></span>
        </div>
      )}
      <div className="pics-bg-sheen"></div>
    </>
  );
}

/* ---- Top nav (consumer-relaxed) ---- */
function PicsNav({ authed, credits, isPro, mobile, current }) {
  return (
    <header className={"pics-nav " + (mobile ? "tight" : "")}>
      <div className="pics-nav-brand">
        <img className="ds-logo white" src={(window.__resources && window.__resources.logoWhite) || "assets/AaaS_Logo_White.png"} alt="AaaS" />
        <img className="ds-logo black" src={(window.__resources && window.__resources.logoBlack) || "assets/AaaS_Logo_Black.png"} alt="AaaS" />
        <span className="ds-seg">pics</span>
      </div>
      {!mobile && !authed && (
        <nav className="pics-nav-links">
          <a className="pics-nav-link">Studio</a>
          <a className="pics-nav-link">Examples</a>
          <a className="pics-nav-link">Pricing</a>
          <a className="pics-nav-link">FAQ</a>
        </nav>
      )}
      {!mobile && authed && (
        <nav className="pics-nav-links">
          <a className={"pics-nav-link" + (current === "studio" ? " is-active" : "")}>Studio</a>
          <a className={"pics-nav-link" + (current === "library" ? " is-active" : "")}>Library</a>
          <a className={"pics-nav-link" + (current === "billing" ? " is-active" : "")}>Credits</a>
        </nav>
      )}
      <div className="pics-nav-actions">
        {authed && (
          <button className="chip cyan" style={{ cursor: "pointer" }}>
            <Icon name="sparkles" size={11} />
            {credits} credits
            {isPro && <span style={{ opacity: 0.6, marginLeft: 4 }}>· PRO</span>}
          </button>
        )}
        {!authed && !mobile && <a className="pics-nav-link">Sign in</a>}
        {!authed && (
          <a className="btn btn-outline sm" style={{ padding: "0.5rem 0.9rem" }}>
            Get started
          </a>
        )}
        {authed && (
          <div className="row gap-8" style={{ alignItems: "center" }}>
            <div style={{
              width: 30, height: 30, borderRadius: "50%",
              background: "linear-gradient(135deg, rgb(var(--circuit-glow) / 0.6), rgb(var(--accent-red) / 0.4))",
              border: "1px solid rgb(var(--text) / 0.15)",
            }}></div>
          </div>
        )}
        {mobile && <button className="pics-nav-link" style={{ padding: 4 }}><Icon name="menu" size={18} /></button>}
      </div>
    </header>
  );
}

/* ---- Footer (.pics-minimal) ---- */
function PicsFooter() {
  return (
    <footer style={{
      padding: "32px 64px", marginTop: 80,
      borderTop: "1px solid var(--border)",
      display: "flex", justifyContent: "space-between", alignItems: "center",
      flexWrap: "wrap", gap: 16,
      fontFamily: "var(--font-jetbrains)", fontSize: 10,
      textTransform: "uppercase", letterSpacing: "0.15em",
      color: "var(--text-muted)"
    }}>
      <div className="row gap-10" style={{ alignItems: "center" }}>
        <span className="status-dot dual"></span>
        <span>aaas<span style={{ color: "rgb(var(--accent-red))" }}>.</span>pics</span>
        <span style={{ opacity: 0.5 }}>· an AaaS surface · v0.1.0</span>
      </div>
      <div className="row gap-20">
        <a className="pics-nav-link">Privacy</a>
        <a className="pics-nav-link">Terms</a>
        <a className="pics-nav-link">Contact</a>
        <a className="pics-nav-link">agents-as-a-service.com →</a>
      </div>
    </footer>
  );
}

/* ---- Onboarding progress bar ---- */
function ProgressBar({ current, steps }) {
  return (
    <div className="pics-progress">
      {steps.map((label, i) => {
        const stepNum = i + 1;
        const state = stepNum < current ? "done" : stepNum === current ? "active" : "pending";
        return (
          <React.Fragment key={label}>
            <div className={"seg " + state}>
              <span className="num">
                {state === "done" ? <Icon name="check" size={11} strokeWidth={2.2} /> : `0${stepNum}`}
              </span>
              <span>{label}</span>
            </div>
            {i < steps.length - 1 && <div className={"bar " + (state === "done" ? "done" : "")}></div>}
          </React.Fragment>
        );
      })}
    </div>
  );
}

/* ---- Stars (for photo tile auto-select score) ---- */
function StarRating({ value }) {
  return (
    <span className="stars">
      {[1,2,3,4,5].map(i => i <= value ? "★" : "·")}
    </span>
  );
}

/* ---- Photo placeholder (greybox, used when no image-slot) ---- */
function PhotoPlaceholder({ label = "Photo", tone = "neutral", aspect, style }) {
  return (
    <div className="ph-placeholder" style={{ position: "relative", aspectRatio: aspect, ...style }}>
      <div className="glyph">
        <Icon name="user" size={18} strokeWidth={1.4} />
      </div>
      <div className="label">{label}</div>
    </div>
  );
}

/* ---- Photo tile (used in select, results, library) ---- */
function PhotoTile({ slot, score, isPicked, isUser, showX, label, slotShape = "rounded", showActions = true }) {
  return (
    <div className={"photo-tile " + (isPicked ? "is-picked " : "") + (isUser ? "is-user " : "")}>
      <div className="ph-frame">
        {slot ? (
          <image-slot
            id={slot}
            style={{ width: "100%", height: "100%" }}
            shape={slotShape}
            placeholder={label || "Drop face photo"}
          ></image-slot>
        ) : (
          <PhotoPlaceholder label={label || "FACE PHOTO"} />
        )}
      </div>
      {showActions && score !== undefined && (
        <div className="ph-meta">
          <span className="ph-score">
            <StarRating value={score} />
          </span>
          {isUser && <span className="ph-tag">picked</span>}
        </div>
      )}
      {showX && <div className="ph-corner-x"><Icon name="x" size={12} /></div>}
    </div>
  );
}

/* ---- Axis row (standard dropdown variant) ---- */
function AxisRow({ label, value, previewSlot }) {
  return (
    <div className="axis-row">
      <div className="axis-label">{label}</div>
      <div className="axis-value">
        <div className="row gap-10" style={{ alignItems: "center", flex: 1 }}>
          <div className="preview">
            {previewSlot ? (
              <image-slot id={previewSlot} style={{ width: "100%", height: "100%" }} shape="rounded" radius="4"></image-slot>
            ) : (
              <div className="ph-placeholder" style={{ position: "absolute" }}>
                <span className="label" style={{ fontSize: 6, letterSpacing: 0.4 }}>STYLE</span>
              </div>
            )}
          </div>
          <span>{value}</span>
        </div>
        <Icon name="chevron-down" size={14} />
      </div>
    </div>
  );
}

/* ---- Visual swatch axis (novel variant) ---- */
function SwatchAxis({ label, options, selectedIdx }) {
  return (
    <div className="axis-row">
      <div className="between" style={{ marginBottom: 10 }}>
        <div className="axis-label">{label}</div>
        <div className="axis-label" style={{ color: "rgb(var(--circuit-glow))" }}>
          {options[selectedIdx]?.label}
        </div>
      </div>
      <div className="swatch-grid">
        {options.map((opt, i) => (
          <div key={opt.label} className={"swatch " + (i === selectedIdx ? "is-selected" : "")}>
            {opt.slot ? (
              <image-slot id={opt.slot} style={{ width: "100%", height: "100%" }} shape="rounded" radius="6"></image-slot>
            ) : (
              <PhotoPlaceholder label={opt.label} />
            )}
            <div className="swatch-label">{opt.label}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ---- Metadata strip (used in results) ---- */
function MetaStrip({ items }) {
  return (
    <div className="row gap-12" style={{ flexWrap: "wrap", alignItems: "center" }}>
      {items.map((item, i) => (
        <React.Fragment key={item.label + i}>
          <div className="col gap-4">
            <div className="label-overline muted" style={{ fontSize: 9 }}>{item.label}</div>
            <div style={{ fontFamily: "var(--font-inter)", fontSize: 13, fontWeight: 500 }}>{item.value}</div>
          </div>
          {i < items.length - 1 && <div style={{
            width: 1, height: 24, background: "var(--border)"
          }}></div>}
        </React.Fragment>
      ))}
    </div>
  );
}

/* ---- IconBadge (small icon in circle, used in how-it-works) ---- */
function IconBadge({ icon, color = "cyan" }) {
  const c = color === "red" ? "var(--accent-red)" : "var(--circuit-glow)";
  return (
    <div style={{
      width: 44, height: 44, borderRadius: "50%",
      background: `rgb(${c} / 0.08)`,
      border: `1px solid rgb(${c} / 0.3)`,
      display: "flex", alignItems: "center", justifyContent: "center",
      color: `rgb(${c})`,
    }}>
      <Icon icon={icon} name={icon} size={20} />
    </div>
  );
}

Object.assign(window, {
  Icon, PicsBackdrop, PicsNav, PicsFooter, ProgressBar,
  StarRating, PhotoPlaceholder, PhotoTile, AxisRow, SwatchAxis,
  MetaStrip, IconBadge,
});
