// ============================================================
// Shared components: Header, Footer, Cart, Buttons, Icons, etc.
// ============================================================

// ── Tiny Lucide-style inline icons (single-stroke, 2px) ─────────────
const I = {};
const _svg = (paths, attrs = {}) => (props) => (
  <svg
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    strokeWidth="2"
    strokeLinecap="round"
    strokeLinejoin="round"
    width={props.size || 18}
    height={props.size || 18}
    {...attrs}
    {...props}
  >
    {paths}
  </svg>
);
I.ArrowRight = _svg(<><line x1="5" y1="12" x2="19" y2="12" /><polyline points="12 5 19 12 12 19" /></>);
I.ArrowLeft  = _svg(<><line x1="19" y1="12" x2="5" y2="12" /><polyline points="12 19 5 12 12 5" /></>);
I.ArrowUpRight = _svg(<><line x1="7" y1="17" x2="17" y2="7" /><polyline points="7 7 17 7 17 17" /></>);
I.Plus       = _svg(<><line x1="12" y1="5" x2="12" y2="19" /><line x1="5" y1="12" x2="19" y2="12" /></>);
I.Minus      = _svg(<line x1="5" y1="12" x2="19" y2="12" />);
I.Check      = _svg(<polyline points="4 12 10 18 20 6" />);
I.X          = _svg(<><line x1="5" y1="5" x2="19" y2="19" /><line x1="19" y1="5" x2="5" y2="19" /></>);
I.Cart       = _svg(<><circle cx="9" cy="20" r="1.5" /><circle cx="18" cy="20" r="1.5" /><path d="M3 4h2l2.6 11.4a2 2 0 0 0 2 1.6h8.4a2 2 0 0 0 2-1.5L22 7H6" /></>);
I.Clock      = _svg(<><circle cx="12" cy="12" r="9" /><polyline points="12 7 12 12 15 14" /></>);
I.Tag        = _svg(<><path d="M3 12V4h8l10 10-8 8L3 12z" /><circle cx="7.5" cy="7.5" r="1" /></>);
I.Box        = _svg(<><path d="M21 8 12 3 3 8v8l9 5 9-5V8z" /><line x1="3" y1="8" x2="12" y2="13" /><line x1="21" y1="8" x2="12" y2="13" /><line x1="12" y1="13" x2="12" y2="21" /></>);
I.Truck      = _svg(<><rect x="2" y="6" width="13" height="11" /><path d="M15 9h4l3 3v5h-7" /><circle cx="6.5" cy="18.5" r="1.5" /><circle cx="17.5" cy="18.5" r="1.5" /></>);
I.Sparkles   = _svg(<><path d="M12 3l1.8 4.2L18 9l-4.2 1.8L12 15l-1.8-4.2L6 9l4.2-1.8z" /><path d="M19 16l.7 1.6L21 18l-1.3.4L19 20l-.7-1.6L17 18l1.3-.4z" /></>);
I.Search     = _svg(<><circle cx="11" cy="11" r="7" /><line x1="20" y1="20" x2="16" y2="16" /></>);
I.User       = _svg(<><circle cx="12" cy="8" r="4" /><path d="M4 21v-1a6 6 0 0 1 6-6h4a6 6 0 0 1 6 6v1" /></>);
I.Menu       = _svg(<><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" /></>);
I.MapPin     = _svg(<><path d="M12 22s7-7 7-12a7 7 0 1 0-14 0c0 5 7 12 7 12z" /><circle cx="12" cy="10" r="2.5" /></>);
I.Shield     = _svg(<path d="M12 3l8 3v6c0 5-3.5 8.5-8 9-4.5-.5-8-4-8-9V6z" />);
I.Zap        = _svg(<polygon points="13 2 4 14 11 14 10 22 20 10 13 10 13 2" />);
I.Globe      = _svg(<><circle cx="12" cy="12" r="9" /><path d="M3 12h18M12 3a13 13 0 0 1 0 18M12 3a13 13 0 0 0 0 18" /></>);
I.Heart      = _svg(<path d="M12 21s-7-4.5-9.3-9.2C.6 7.6 4 4 7.4 4 9.5 4 11 5 12 6.5 13 5 14.5 4 16.6 4 20 4 23.4 7.6 21.3 11.8 19 16.5 12 21 12 21z" />);
I.Mail       = _svg(<><rect x="3" y="5" width="18" height="14" rx="2" /><polyline points="3 7 12 13 21 7" /></>);
I.Phone      = _svg(<path d="M5 4h4l2 5-3 2a12 12 0 0 0 5 5l2-3 5 2v4a2 2 0 0 1-2 2A16 16 0 0 1 3 6a2 2 0 0 1 2-2z" />);

// Generic platform "from" logo: a small monogram tile
function PlatformTile({ p, size = 36 }) {
  return (
    <div style={{
      width: size, height: size, borderRadius: 6,
      background: p.color, color: "#fff",
      display: "inline-flex", alignItems: "center", justifyContent: "center",
      fontFamily: "var(--font-display)", fontWeight: 900, fontSize: size * 0.42,
      letterSpacing: "-0.02em",
    }}>{p.short}</div>
  );
}

// Aartisan mark (logo without wordmark)
function Mark({ size = 36 }) {
  return (
    <svg viewBox="340 380 342 342" width={size} height={size} aria-hidden="true">
      <rect x="359.2" y="399.5" width="303.2" height="303.2" fill="#FFBFB7" />
      <polygon points="510.8,479 389.1,702.7 632.5,702.7" fill="#320D6D" />
      <rect x="482.2" y="628" width="57.2" height="57.2" transform="rotate(-45 510.8 656.6)" fill="#FFD447" />
      <path fillRule="evenodd" fill="#700353" d="M340.1,380.4 H681.5 V721.8 H340.1 Z M359.2,399.5 V702.7 H662.4 V399.5 Z" />
    </svg>
  );
}

// ── Header ──────────────────────────────────────────────────────────
function Header({ current, onNav, headerStyle = "sticky" }) {
  const [scrolled, setScrolled] = React.useState(false);
  React.useEffect(() => {
    const fn = () => setScrolled(window.scrollY > 8);
    fn();
    window.addEventListener("scroll", fn, { passive: true });
    return () => window.removeEventListener("scroll", fn);
  }, []);
  React.useEffect(() => {
    if (headerStyle === "float") document.body.classList.add("float-header");
    else document.body.classList.remove("float-header");
  }, [headerStyle]);

  return (
    <header className={`site-header${scrolled ? " scrolled" : ""}${headerStyle === "float" ? " float" : ""}`}>
      <div className="header-inner">
        <button className="brand" onClick={() => onNav("home")}>
          <Mark size={36} />
          <span className="brand-name">Aartisan</span>
        </button>
        <nav className="nav">
          {NAV.filter(n => n.id !== "home").map(n => (
            <button
              key={n.id}
              className={`nav-link ${current === n.id ? "active" : ""}`}
              onClick={() => onNav(n.id)}
            >{n.label}</button>
          ))}
        </nav>
        <div className="header-actions">
          <button className="btn btn-accent btn-sm" onClick={() => onNav("build")}>
            <span className="header-cta-full">Build a migration package</span>
            <span className="header-cta-short">Get a quote</span>
            <I.ArrowRight size={14} />
          </button>
        </div>
      </div>
    </header>
  );
}

// ── Footer ──────────────────────────────────────────────────────────
function Footer({ onNav }) {
  return (
    <footer className="site-footer">
      <div className="container">
        <div className="footer-grid">
          <div className="footer-col">
            <div className="footer-mark">
              <Mark size={44} />
              <span>Aartisan</span>
            </div>
            <p style={{ color: "var(--color-blush-200)", maxWidth: 360, marginTop: 16, lineHeight: 1.6 }}>
              We move ecommerce stores to Shopify — smoothly, securely, stress-free. Buy a package, skip the sales call, get it shipped.
            </p>
          </div>
          <div className="footer-col">
            <h4>Shop</h4>
            <ul>
              <li><a onClick={() => onNav("build")}>Build a package</a></li>
              </ul>
          </div>
          <div className="footer-col">
            <h4>Aartisan</h4>
            <ul>
              <li><a onClick={() => onNav("cases")}>Case studies</a></li>
              <li><a onClick={() => onNav("about")}>About</a></li>
            </ul>
          </div>
          <div className="footer-col">
            <h4>Help</h4>
            <ul>
              <li><a onClick={() => onNav("faq")}>FAQ</a></li>
              <li><a href="mailto:blake@aartisan.io">blake@aartisan.io</a></li>
            </ul>
          </div>
        </div>
        <div className="footer-bottom">
          <div>© 2026 Aartisan Ltd. · aartisan.io · A Shopify Partner since 2026</div>
          <div style={{ display: "flex", gap: 16 }}>
            <a onClick={() => onNav("privacy")} style={{ cursor: "pointer" }}>Privacy</a>
          </div>
        </div>
      </div>
    </footer>
  );
}

// ── Product card ────────────────────────────────────────────────────
function ProductCard({ p, onOpen, onAdd, featured = false }) {
  return (
    <div className={`product-card ${featured ? "product-card-featured" : ""}`} role="article">
      <div className="product-card-header">
        <div>
          <div style={{ display: "flex", gap: 8, alignItems: "center", marginBottom: 8, flexWrap: "wrap" }}>
            <span className="product-tag plain">{p.tier}</span>
            {p.badge && <span className="product-tag">{p.badge}</span>}
          </div>
          <h3 className="product-title">{p.title}</h3>
        </div>
        <div style={{ textAlign: "right" }}>
          <div className="product-price">{fmtPrice(p.price)}</div>
          <div className="product-price-suffix">{p.priceSuffix}</div>
        </div>
      </div>
      <p style={{ color: "var(--fg-2)", lineHeight: 1.55, margin: 0 }}>{p.summary}</p>
      <div className="product-meta">
        {p.duration && <span className="product-meta-item"><I.Clock size={14} /> {p.duration}</span>}
        {p.bestFor && <span className="product-meta-item"><I.Tag size={14} /> {p.bestFor}</span>}
      </div>
      <div style={{ display: "flex", gap: 8, marginTop: 8 }}>
        <button className="btn btn-sm" onClick={() => onAdd(p)} style={{ flex: 1 }}>
          <I.Plus size={14} /> Add to cart
        </button>
        <button className="btn btn-ghost btn-sm" onClick={() => onOpen(p)}>
          Details
        </button>
      </div>
    </div>
  );
}

// ── Reveal-on-scroll wrapper ────────────────────────────────────────
function Reveal({ children, delay = 0, as = "div", ...rest }) {
  const ref = React.useRef(null);
  const [seen, setSeen] = React.useState(false);
  React.useEffect(() => {
    if (!ref.current) return;
    // Immediate check: if element is already in viewport, reveal now.
    const rect = ref.current.getBoundingClientRect();
    const vh = window.innerHeight || document.documentElement.clientHeight;
    if (rect.top < vh + 40 && rect.bottom > 0) {
      setSeen(true);
      return;
    }
    // Otherwise observe for entry — with a safety fallback in case IO never fires
    let observed = true;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => { if (e.isIntersecting) setSeen(true); });
    }, { threshold: 0.1, rootMargin: "0px 0px -40px 0px" });
    io.observe(ref.current);
    const fallback = setTimeout(() => { if (observed) setSeen(true); }, 1500);
    return () => { observed = false; io.disconnect(); clearTimeout(fallback); };
  }, []);
  const Tag = as;
  return (
    <Tag
      ref={ref}
      className={`reveal ${seen ? "in" : ""} ${rest.className || ""}`}
      style={{ ...(rest.style || {}), "--reveal-delay": `${delay}ms` }}
      {...Object.fromEntries(Object.entries(rest).filter(([k]) => !["className","style"].includes(k)))}
    >
      {children}
    </Tag>
  );
}

// ── Stat band ───────────────────────────────────────────────────────
function StatBand() {
  return (
    <div className="stat-band container">
      {STATS.map((s, i) => (
        <Reveal key={i} delay={i * 80}>
          <div className="stat">
            <div className="stat-num">{s.num}</div>
            <div className="stat-label">{s.label}</div>
          </div>
        </Reveal>
      ))}
    </div>
  );
}

// ── Marquee strip ──────────────────────────────────────────────────
function Marquee({ items }) {
  const content = items.flatMap((it, i) => [
    <span key={`t${i}`}>{it}</span>,
    <span key={`d${i}`} className="diamond" style={{ width: 12, height: 12, background: "currentColor" }} />,
  ]);
  return (
    <div className="marquee" aria-hidden="true">
      <div className="marquee-track">
        <span>{content}</span>
        <span>{content}</span>
      </div>
    </div>
  );
}

// ── Toast (cart-add confirmation) ──────────────────────────────────
function Toast({ message, onClose }) {
  React.useEffect(() => {
    const t = setTimeout(onClose, 2200);
    return () => clearTimeout(t);
  }, [onClose]);
  return (
    <div className="toast">
      <I.Check size={16} /> {message}
    </div>
  );
}

// Rubber stamp (SVG with rough edges)
function Stamp({ children, color = "var(--color-plum-700)", rotate = -4, scale = 1 }) {
  return (
    <span
      className="rubber-stamp"
      style={{
        color,
        transform: `rotate(${rotate}deg) scale(${scale})`,
        filter: "url(#stamp-rough)",
      }}
    >{children}</span>
  );
}

// Postmark
function Postmark({ label = "Aartisan · Migration", date = "EST 2019", size = 110, rotate = -10 }) {
  return (
    <div className="postmark" style={{ width: size, height: size, transform: `rotate(${rotate}deg)` }}>
      <div>
        {label}<br />
        <span style={{ fontSize: "0.6rem", opacity: 0.8 }}>★ {date} ★</span>
      </div>
    </div>
  );
}

// SVG filter defs (for rough stamp edges) — render once at top of app
function SvgDefs() {
  return (
    <svg width="0" height="0" style={{ position: "absolute" }} aria-hidden="true">
      <defs>
        <filter id="stamp-rough" x="-5%" y="-5%" width="110%" height="110%">
          <feTurbulence baseFrequency="0.9" numOctaves="2" result="noise" />
          <feDisplacementMap in="SourceGraphic" in2="noise" scale="2.4" />
        </filter>
      </defs>
    </svg>
  );
}

Object.assign(window, {
  I, PlatformTile, Mark, Header, Footer, ProductCard,
  Reveal, StatBand, Marquee, Toast, Stamp, Postmark, SvgDefs,
});
