// components.jsx — reusable atoms: icons, logo, product card, drawer, etc.

const { useState, useEffect, useRef, createContext, useContext, useMemo } = React;

/* ============================ ICONS ============================ */
const Icon = ({ name, size = 20, stroke = 1.6 }) => {
  const paths = {
    search: <><circle cx="11" cy="11" r="7" /><path d="m20 20-3-3" /></>,
    heart: <path d="M12 21s-7-4.5-9.5-9C.8 8.5 3 4 7 4c2 0 3.5 1 5 3 1.5-2 3-3 5-3 4 0 6.2 4.5 4.5 8-2.5 4.5-9.5 9-9.5 9z" />,
    bag: <><path d="M5 7h14l-1 13H6L5 7z" /><path d="M8 7V5a4 4 0 1 1 8 0v2" /></>,
    user: <><circle cx="12" cy="8" r="4" /><path d="M4 21c1.5-4 4.5-6 8-6s6.5 2 8 6" /></>,
    menu: <><path d="M3 7h18M3 12h18M3 17h18" /></>,
    close: <><path d="M5 5l14 14M19 5L5 19" /></>,
    chev: <path d="m6 9 6 6 6-6" />,
    chevR: <path d="m9 6 6 6-6 6" />,
    chevL: <path d="m15 6-6 6 6 6" />,
    plus: <><path d="M12 5v14M5 12h14" /></>,
    minus: <path d="M5 12h14" />,
    sun: <><circle cx="12" cy="12" r="4" /><path d="M12 3v2M12 19v2M3 12h2M19 12h2M5.6 5.6l1.4 1.4M17 17l1.4 1.4M5.6 18.4 7 17M17 7l1.4-1.4" /></>,
    moon: <path d="M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8z" />,
    truck: <><path d="M3 7h12v9H3z"/><path d="M15 10h4l2 3v3h-6"/><circle cx="7" cy="18" r="2"/><circle cx="17" cy="18" r="2"/></>,
    box: <><path d="M3 7l9-4 9 4-9 4-9-4z"/><path d="M3 7v10l9 4 9-4V7"/><path d="M12 11v10"/></>,
    chart: <><path d="M4 20V10M10 20V4M16 20v-7M22 20H2"/></>,
    cog: <><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1.1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1c.5.5 1.2.7 1.8.3.6-.2 1-.8 1-1.5V3a2 2 0 1 1 4 0v.1c0 .7.4 1.3 1 1.5.6.4 1.3.2 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8c.2.6.8 1 1.5 1H21a2 2 0 1 1 0 4h-.1c-.7 0-1.3.4-1.5 1z"/></>,
    tag: <><path d="M20 12 12 4H4v8l8 8 8-8z"/><circle cx="7.5" cy="7.5" r="1"/></>,
    flame: <path d="M12 3s4 4 4 8a4 4 0 0 1-8 0c0-1.5 1-2.5 1-2.5S8 11 8 14a4 4 0 0 0 8 0c0-5-4-11-4-11z"/>,
    arrowR: <><path d="M5 12h14"/><path d="m13 5 7 7-7 7"/></>,
    arrowUR: <><path d="M7 17 17 7"/><path d="M8 7h9v9"/></>,
    check: <path d="m5 12 5 5 9-12"/>,
    dot: <circle cx="12" cy="12" r="3"/>,
    eye: <><path d="M2 12s4-7 10-7 10 7 10 7-4 7-10 7S2 12 2 12z"/><circle cx="12" cy="12" r="3"/></>,
    edit: <><path d="M12 20h9"/><path d="M16.5 3.5a2.1 2.1 0 1 1 3 3L7 19l-4 1 1-4 12.5-12.5z"/></>,
    trash: <><path d="M3 6h18"/><path d="M8 6V4h8v2"/><path d="M19 6 18 20H6L5 6"/></>,
    instagram: <><rect x="3" y="3" width="18" height="18" rx="5"/><circle cx="12" cy="12" r="4"/><circle cx="17.5" cy="6.5" r=".8" fill="currentColor" stroke="none"/></>,
    spotify: <><circle cx="12" cy="12" r="9"/><path d="M7 10c4-1 8-1 11 1M8 13c3-1 6-1 9 1M9 16c2-1 4-1 6 0"/></>,
    pin: <><path d="M12 22s-7-7-7-12a7 7 0 1 1 14 0c0 5-7 12-7 12z"/><circle cx="12" cy="10" r="2.5"/></>,
  };
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={stroke} strokeLinecap="round" strokeLinejoin="round">
      {paths[name]}
    </svg>
  );
};

/* ============================ LOGO ============================ */
const OrahMark = ({ size = 44, withRing = true }) => (
  <span style={{
    display: "inline-grid", placeItems: "center",
    width: size, height: size, borderRadius: "50%",
    background: "var(--orah-blue-700)",
    border: withRing ? "2px solid var(--bg-card)" : "none",
    overflow: "hidden",
    boxShadow: "inset 0 0 0 1px rgba(255,255,255,0.1)",
  }}>
    <img src="assets/orah-logo.png" alt="ORAH" style={{ width: "100%", height: "100%", objectFit: "cover" }} />
  </span>
);

const OrahWordmark = ({ size = 32 }) => (
  <span style={{ fontFamily: "var(--f-display)", fontSize: size, lineHeight: 1, color: "var(--brand)", letterSpacing: "0.01em" }}>
    ORAH<span style={{ fontSize: size * 0.34, marginLeft: 6, letterSpacing: "0.2em", verticalAlign: "middle", color: "var(--ink-soft)" }}>CULTURE</span>
  </span>
);

/* ============================ SHOP CTX ============================ */
const ShopCtx = createContext(null);
const useShop = () => useContext(ShopCtx);

const USERS = {
  amanda: { id: "amanda", firstName: "Amanda", fullName: "Amanda Petroski", email: "amanda@orahculture.com" },
  miguel: { id: "miguel", firstName: "Miguel", fullName: "Miguel Braido", email: "miguel@orahculture.com" },
};

function ShopProvider({ children }) {
  const [page, setPage] = useState(["home"]);  // stack
  const [cart, setCart] = useState([]);
  const [wish, setWish] = useState([]);
  const [drawer, setDrawer] = useState(null); // 'menu' | 'cart' | 'wish' | 'search' | null
  const [currentUser, setCurrentUserState] = useState(() => {
    if (typeof window === "undefined") return null;
    const saved = window.localStorage.getItem("orah:currentUser");
    return saved && USERS[saved] ? USERS[saved] : null;
  });
  const [userSelectorOpen, setUserSelectorOpen] = useState(false);
  const [pendingPage, setPendingPage] = useState(null);

  const setCurrentUser = (id) => {
    if (!USERS[id]) return;
    window.localStorage.setItem("orah:currentUser", id);
    setCurrentUserState(USERS[id]);
  };
  const clearCurrentUser = () => {
    window.localStorage.removeItem("orah:currentUser");
    setCurrentUserState(null);
  };

  const ADMIN_PAGES = new Set(["admin", "account"]);

  const goto = (p, params) => {
    const name = typeof p === "string" ? p : p.name;
    if (ADMIN_PAGES.has(name) && !currentUser) {
      setPendingPage({ name, params });
      setUserSelectorOpen(true);
      return;
    }
    setPage([typeof p === "string" ? { name: p, params } : p]);
    window.scrollTo({ top: 0, behavior: "instant" });
    setDrawer(null);
  };
  const push = (p, params) => {
    const name = typeof p === "string" ? p : p.name;
    if (ADMIN_PAGES.has(name) && !currentUser) {
      setPendingPage({ name, params });
      setUserSelectorOpen(true);
      return;
    }
    setPage((s) => [...s, { name: p, params }]);
    window.scrollTo({ top: 0, behavior: "instant" });
    setDrawer(null);
  };

  const confirmUser = (id) => {
    setCurrentUser(id);
    setUserSelectorOpen(false);
    if (pendingPage) {
      setPage([{ name: pendingPage.name, params: pendingPage.params }]);
      window.scrollTo({ top: 0, behavior: "instant" });
      setDrawer(null);
      setPendingPage(null);
    }
  };
  const cancelUserSelector = () => {
    setUserSelectorOpen(false);
    setPendingPage(null);
  };
  const back = () => setPage((s) => s.length > 1 ? s.slice(0, -1) : s);
  const current = page[page.length - 1];
  const currentName = typeof current === "string" ? current : current.name;
  const currentParams = typeof current === "string" ? {} : (current.params || {});

  const addToCart = (productId, size = "M", qty = 1) => {
    setCart((c) => {
      const i = c.findIndex((x) => x.productId === productId && x.size === size);
      if (i >= 0) {
        const copy = [...c]; copy[i] = { ...copy[i], qty: copy[i].qty + qty }; return copy;
      }
      return [...c, { productId, size, qty }];
    });
  };
  const updateCart = (idx, qty) => {
    setCart((c) => qty <= 0 ? c.filter((_, i) => i !== idx) : c.map((x, i) => i === idx ? { ...x, qty } : x));
  };
  const toggleWish = (productId) => {
    setWish((w) => w.includes(productId) ? w.filter((x) => x !== productId) : [...w, productId]);
  };

  const value = {
    page: currentName, params: currentParams, goto, push, back,
    cart, addToCart, updateCart, clearCart: () => setCart([]),
    wish, toggleWish,
    drawer, setDrawer,
    currentUser, setCurrentUser, clearCurrentUser,
    userSelectorOpen, confirmUser, cancelUserSelector,
  };

  return (
    <ShopCtx.Provider value={value}>
      {children}
      {userSelectorOpen && <UserSelectorModal onPick={confirmUser} onClose={cancelUserSelector} />}
    </ShopCtx.Provider>
  );
}

function UserSelectorModal({ onPick, onClose }) {
  return (
    <div
      onClick={onClose}
      style={{
        position: "fixed", inset: 0, zIndex: 9999,
        background: "rgba(8, 12, 24, 0.72)",
        backdropFilter: "blur(6px)",
        display: "grid", placeItems: "center",
        padding: 20,
      }}
    >
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          width: "100%", maxWidth: 460,
          background: "var(--bg)", color: "var(--ink)",
          borderRadius: 16, padding: 32,
          boxShadow: "0 30px 80px rgba(0,0,0,0.5)",
          border: "1px solid var(--ink-line)",
        }}
      >
        <div className="mono" style={{ fontSize: 11, opacity: 0.6, textTransform: "uppercase", letterSpacing: "0.16em" }}>acesso restrito</div>
        <h2 style={{ fontFamily: "var(--f-display)", fontSize: 32, lineHeight: 1, margin: "12px 0 8px", textTransform: "uppercase" }}>quem está acessando?</h2>
        <p className="muted" style={{ fontSize: 14, marginBottom: 24 }}>Selecione abaixo para entrar no painel.</p>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          {Object.values(USERS).map((u) => (
            <button
              key={u.id}
              onClick={() => onPick(u.id)}
              style={{
                appearance: "none", cursor: "pointer",
                background: "var(--bg-card)", color: "var(--ink)",
                border: "1px solid var(--ink-line)", borderRadius: 12,
                padding: "20px 16px", textAlign: "left",
                fontFamily: "inherit",
                transition: "border-color .15s, transform .15s",
              }}
              onMouseEnter={(e) => { e.currentTarget.style.borderColor = "var(--brand)"; e.currentTarget.style.transform = "translateY(-2px)"; }}
              onMouseLeave={(e) => { e.currentTarget.style.borderColor = "var(--ink-line)"; e.currentTarget.style.transform = "translateY(0)"; }}
            >
              <div style={{
                width: 48, height: 48, borderRadius: "50%",
                background: "var(--brand)", color: "var(--on-brand)",
                display: "grid", placeItems: "center",
                fontFamily: "var(--f-display)", fontSize: 22,
                marginBottom: 14,
              }}>{u.firstName[0]}</div>
              <div style={{ fontFamily: "var(--f-display)", fontSize: 22, textTransform: "uppercase", lineHeight: 1 }}>{u.firstName}</div>
              <div className="mono muted" style={{ fontSize: 11, marginTop: 6 }}>{u.fullName.split(" ").slice(1).join(" ").toLowerCase()}</div>
            </button>
          ))}
        </div>
        <button
          onClick={onClose}
          style={{
            marginTop: 20, width: "100%",
            appearance: "none", cursor: "pointer",
            background: "transparent", color: "var(--ink-soft)",
            border: 0, padding: 10, fontFamily: "inherit", fontSize: 13,
          }}
        >cancelar</button>
      </div>
    </div>
  );
}

/* ============================ PRODUCT VISUAL ============================ */
function ProductVisual({ product, large = false, minimal = false }) {
  // a "shirt" mock: colored area + quote + verse + ORAH wordmark
  return (
    <div style={{
      width: "100%", height: "100%",
      background: product.bg,
      color: product.fg,
      display: "grid", placeItems: "center",
      position: "relative",
      padding: large ? 48 : 18,
      overflow: "hidden",
    }}>
      <div style={{ textAlign: "center", maxWidth: large ? "80%" : "94%" }}>
        <div style={{
          fontFamily: "var(--f-display)",
          fontSize: large ? "clamp(28px, 4.5cqw, 64px)" : 22,
          lineHeight: 0.95,
          textTransform: "uppercase",
          letterSpacing: "0.01em",
          textWrap: "balance",
        }}>{product.quote}</div>
        <div style={{
          fontFamily: "var(--f-hand)",
          fontSize: large ? 24 : 13,
          marginTop: 10,
          opacity: 0.85,
        }}>{product.verse}</div>
      </div>
      {!minimal && (<>
        <div style={{
          position: "absolute",
          bottom: large ? 24 : 8,
          right: large ? 28 : 10,
          fontFamily: "var(--f-mono)",
          fontSize: large ? 11 : 9,
          letterSpacing: "0.18em",
          opacity: 0.7,
        }}>ORAH · {product.line.toUpperCase()}</div>
        <div style={{
          position: "absolute",
          top: large ? 24 : 8,
          left: large ? 28 : 10,
          fontFamily: "var(--f-mono)",
          fontSize: large ? 11 : 9,
          letterSpacing: "0.18em",
          opacity: 0.7,
        }}>{product.drop.toUpperCase()}</div>
      </>)}
    </div>
  );
}

/* ============================ PRODUCT CARD ============================ */
function ProductCard({ product, onClick, cardStyle = "clean" }) {
  const { wish, toggleWish } = useShop();
  const liked = wish.includes(product.id);

  return (
    <div className="product-card" onClick={() => onClick && onClick(product)}>
      <div className="img" style={{ position: "relative" }}>
        <ProductVisual product={product} />
        {product.tag && (
          <span className="badge fire" style={{ position: "absolute", top: 12, left: 12 }}>
            {product.tag}
          </span>
        )}
        <button
          className="icon-btn"
          onClick={(e) => { e.stopPropagation(); toggleWish(product.id); }}
          style={{
            position: "absolute", top: 8, right: 8,
            background: "var(--bg-card)",
            color: liked ? "var(--accent)" : "var(--ink)",
            width: 36, height: 36,
          }}
        >
          <Icon name="heart" size={16} />
        </button>

        {cardStyle === "label" && (
          <div style={{
            position: "absolute", bottom: 12, left: 12, right: 12,
            background: "var(--bg-card)", color: "var(--ink)",
            padding: "8px 10px",
            display: "flex", justifyContent: "space-between",
            fontFamily: "var(--f-mono)", fontSize: 10, letterSpacing: 0.1, textTransform: "uppercase",
          }}>
            <span>ORAH / {product.line}</span>
            <span>{product.id.toUpperCase()}</span>
          </div>
        )}
      </div>
      <div className="meta">
        <div className="row" style={{ justifyContent: "space-between", gap: 8 }}>
          <div>
            <div style={{ fontFamily: "var(--f-display)", fontSize: 22, textTransform: "uppercase", lineHeight: 1 }}>
              {product.name}
            </div>
            <div className="mono muted" style={{ marginTop: 4 }}>{product.line} · {product.drop}</div>
          </div>
          <div className="price" style={{ whiteSpace: "nowrap" }}>
            {product.oldPrice && <span style={{ textDecoration: "line-through", color: "var(--ink-soft)", marginRight: 6, fontSize: 12 }}>R$ {product.oldPrice.toFixed(2).replace(".", ",")}</span>}
            R$ {product.price.toFixed(2).replace(".", ",")}
          </div>
        </div>
      </div>
    </div>
  );
}

/* ============================ STAMP / SEAL ============================ */
function Stamp({ children, rotate = -8, color = "var(--accent)" }) {
  return (
    <span style={{
      display: "inline-block",
      transform: `rotate(${rotate}deg)`,
      border: `2px solid ${color}`,
      color,
      padding: "6px 12px",
      fontFamily: "var(--f-mono)",
      fontSize: 11,
      fontWeight: 700,
      letterSpacing: "0.16em",
      textTransform: "uppercase",
      borderRadius: 4,
    }}>{children}</span>
  );
}

/* expose */
Object.assign(window, { Icon, OrahMark, OrahWordmark, ShopProvider, useShop, ShopCtx, ProductVisual, ProductCard, Stamp });
