// ============================================================
// Shared UI - FreshWave Digital Studio
// ============================================================
const { useState, useEffect, useRef } = React;

// Accent color helpers ----------------------------------------------------
const ACCENT_VAR = {
  cyan: 'var(--cyan)',
  magenta: 'var(--magenta)',
  'vapor-purple': 'var(--vapor-purple)',
  sunset: 'var(--sunset)',
};
const accentHsl = (a, alpha) =>
  alpha == null ? `hsl(${ACCENT_VAR[a] || ACCENT_VAR.cyan})` : `hsl(${ACCENT_VAR[a] || ACCENT_VAR.cyan} / ${alpha})`;

const FW_CONFIG = window.FRESHWAVE_CONFIG || {};
const FW_THEME_URL = (FW_CONFIG.themeUrl || '/wp-content/themes/freshwave').replace(/\/$/, '');
const fwAsset = (path) => FW_THEME_URL ? `${FW_THEME_URL}/${path.replace(/^\//, '')}` : path;

// Navigate helper (hash router) -------------------------------------------
const go = (path) => { window.location.hash = path; };

// Click sparks -------------------------------------------------------------
const SPARK_COLORS = ['var(--cyan)', 'var(--magenta)', 'var(--vapor-purple)', 'var(--sunset)'];

function triggerButtonSparks(event, force = false) {
  const target = event.currentTarget || event.target;
  if (!target || target.disabled || target.getAttribute('aria-disabled') === 'true') return;
  if (window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;
  if (!force && Math.random() > 0.58) return;

  const rect = target.getBoundingClientRect();
  const x = event.clientX || rect.left + rect.width / 2;
  const y = event.clientY || rect.top + rect.height / 2;
  const burst = document.createElement('span');
  burst.className = 'fw-spark-burst';
  burst.style.left = `${x}px`;
  burst.style.top = `${y}px`;

  const count = force ? 10 : 5 + Math.floor(Math.random() * 4);
  for (let i = 0; i < count; i += 1) {
    const spark = document.createElement('i');
    const angle = -165 + Math.random() * 330;
    const color = SPARK_COLORS[Math.floor(Math.random() * SPARK_COLORS.length)];
    spark.style.setProperty('--spark-color', `hsl(${color})`);
    spark.style.setProperty('--spark-angle', `${angle}deg`);
    spark.style.setProperty('--spark-distance', `${30 + Math.random() * 54}px`);
    spark.style.setProperty('--spark-drop', `${-8 + Math.random() * 18}px`);
    spark.style.setProperty('--spark-width', `${6 + Math.random() * 9}px`);
    spark.style.setProperty('--spark-speed', `${520 + Math.random() * 180}ms`);
    spark.style.setProperty('--spark-delay', `${Math.random() * 45}ms`);
    burst.appendChild(spark);
  }

  document.body.appendChild(burst);
  window.setTimeout(() => burst.remove(), 820);
}

// Minimal icon set (simple arrows / marks only) ---------------------------
function Icon({ name, className = 'h-4 w-4', stroke = 2, style }) {
  const common = {
    className, style, viewBox: '0 0 24 24', fill: 'none',
    stroke: 'currentColor', strokeWidth: stroke, strokeLinecap: 'round', strokeLinejoin: 'round',
  };
  switch (name) {
    case 'arrow-right': return (<svg {...common}><line x1="5" y1="12" x2="19" y2="12" /><polyline points="12 5 19 12 12 19" /></svg>);
    case 'arrow-up-right': return (<svg {...common}><line x1="7" y1="17" x2="17" y2="7" /><polyline points="7 7 17 7 17 17" /></svg>);
    case 'arrow-left': return (<svg {...common}><line x1="19" y1="12" x2="5" y2="12" /><polyline points="12 19 5 12 12 5" /></svg>);
    case 'check': return (<svg {...common}><polyline points="20 6 9 17 4 12" /></svg>);
    case 'menu': return (<svg {...common}><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" /></svg>);
    case 'close': return (<svg {...common}><line x1="18" y1="6" x2="6" y2="18" /><line x1="6" y1="6" x2="18" y2="18" /></svg>);
    case 'spinner': return (<svg {...common} className={className + ' animate-spin'}><path d="M21 12a9 9 0 1 1-6.219-8.56" /></svg>);
    case 'layers': return (<svg {...common}><polygon points="12 2 2 7 12 12 22 7 12 2" /><polyline points="2 17 12 22 22 17" /><polyline points="2 12 12 17 22 12" /></svg>);
    default: return null;
  }
}

// Button ------------------------------------------------------------------
function Button({ children, variant = 'default', size = 'md', className = '', as = 'button', onPointerDown, ...props }) {
  const base = 'inline-flex items-center justify-center gap-2 rounded-md font-heading uppercase tracking-wider transition-all duration-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:opacity-50 disabled:pointer-events-none select-none';
  const sizes = {
    md: 'h-12 px-6 text-xs',
    lg: 'h-14 px-8 text-sm',
    sm: 'h-11 px-4 text-xs',
  };
  const variants = {
    default: 'bg-primary text-primary-foreground glow-rest-cyan hover:shadow-[0_0_30px_hsl(var(--cyan)/0.7)] hover:-translate-y-0.5',
    secondary: 'bg-secondary text-secondary-foreground glow-rest-magenta hover:shadow-[0_0_30px_hsl(var(--magenta)/0.7)] hover:-translate-y-0.5',
    outline: 'border border-border bg-transparent text-foreground hover:border-primary hover:text-primary hover:shadow-[0_0_18px_hsl(var(--cyan)/0.35)]',
    ghost: 'bg-transparent text-foreground hover:bg-muted',
  };
  const Tag = as;
  const handlePointerDown = (event) => {
    triggerButtonSparks(event);
    if (onPointerDown) onPointerDown(event);
  };
  return (
    <Tag className={`${base} spark-button ${sizes[size]} ${variants[variant]} ${className}`} {...props} onPointerDown={handlePointerDown}>
      {children}
    </Tag>
  );
}

// Striped placeholder (user drops photos later) ---------------------------
function Placeholder({ label, accent = 'cyan', className = '', glow = false, children }) {
  return (
    <div
      className={`ph-stripes relative flex items-center justify-center overflow-hidden ${className}`}
      style={{ '--ph-accent': accentHsl(accent), ...(glow ? { boxShadow: `inset 0 0 80px ${accentHsl(accent, 0.18)}` } : {}) }}
    >
      <div className="absolute inset-3 border border-dashed" style={{ borderColor: accentHsl(accent, 0.4) }}></div>
      {children || (
        <div className="relative z-10 px-4 text-center">
          <div className="ph-label font-mono text-[10px] uppercase tracking-[0.25em]" style={{ color: accentHsl(accent, 0.9) }}>
            {label}
          </div>
        </div>
      )}
    </div>
  );
}

function LogoImage({ variant = 'emblem', alt = 'FreshWave logo', className = '' }) {
  const [failed, setFailed] = useState(false);
  const src = variant === 'full' ? fwAsset('assets/freshwave-logo.png') : fwAsset('assets/fw-emblem.png');

  if (!failed) {
    return <img src={src} alt={alt} className={className} onError={() => setFailed(true)} />;
  }

  if (variant === 'full') {
    return (
      <span className={`lit-logo flex min-h-32 w-full items-center justify-center rounded-2xl border border-primary/50 bg-background px-6 py-8 text-center font-heading text-3xl tracking-[0.12em] text-primary text-glow-cyan ${className}`}>
        FRESHWAVE
      </span>
    );
  }

  return (
    <span className={`lit-logo inline-flex h-11 min-w-11 items-center justify-center rounded-md border border-primary/50 bg-background px-2 font-heading text-sm tracking-wider text-primary text-glow-cyan ${className}`}>
      FW
    </span>
  );
}

// Section eyebrow ---------------------------------------------------------
function Eyebrow({ children, accent = 'cyan' }) {
  return (
    <div className="mb-4 flex items-center gap-3 font-mono text-xs uppercase tracking-[0.25em] neon-text-soft" style={{ color: accentHsl(accent) }}>
      <span className="neon-glow inline-block h-1.5 w-1.5 rotate-45" style={{ background: accentHsl(accent), color: accentHsl(accent) }}></span>
      {children}
    </div>
  );
}

const TRUST_POINTS = ['No payment today', 'Quote within 72h', 'Material help included'];

function TrustStrip({ className = '' }) {
  return (
    <div className={`flex flex-wrap gap-2 ${className}`}>
      {TRUST_POINTS.map((point, idx) => (
        <span
          key={point}
          className="inline-flex items-center gap-2 rounded-md border border-border bg-card/70 px-3 py-2 font-data text-sm font-bold uppercase tracking-[0.04em] text-muted-foreground"
          style={{ boxShadow: `0 0 18px ${accentHsl(idx === 1 ? 'magenta' : 'cyan', 0.08)}` }}
        >
          <Icon name="check" className="h-3.5 w-3.5" stroke={3} style={{ color: accentHsl(idx === 1 ? 'magenta' : 'cyan') }} />
          {point}
        </span>
      ))}
    </div>
  );
}

function BeforePrintPanel({ className = '' }) {
  const checks = ['Price locked first', 'Timeline confirmed', 'Reference details checked'];
  return (
    <div
      className={`charged-panel mx-auto max-w-4xl rounded-2xl border border-border bg-card/90 p-5 md:p-6 ${className}`}
      style={{ '--panel-accent': accentHsl('cyan') }}
    >
      <div className="grid gap-5 md:grid-cols-[0.8fr_1.4fr] md:items-center">
        <div>
          <div className="mb-2 font-mono text-[10px] uppercase tracking-[0.25em] text-primary">FreshWave promise</div>
          <h3 className="crt-head font-heading text-2xl tracking-wide">Before we print</h3>
        </div>
        <div>
          <p className="mb-4 text-sm leading-relaxed text-muted-foreground">
            We confirm price, size, finish, timeline and reference details first. You only move forward when the quote feels right.
          </p>
          <div className="flex flex-wrap gap-2">
            {checks.map((check, idx) => (
              <span key={check} className="inline-flex items-center gap-2 rounded-md border border-border bg-background/55 px-3 py-2 font-data text-sm font-bold uppercase tracking-[0.04em] text-muted-foreground">
                <Icon name="check" className="h-3.5 w-3.5" stroke={3} style={{ color: accentHsl(idx === 1 ? 'magenta' : 'cyan') }} />
                {check}
              </span>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

// Header ------------------------------------------------------------------
const NAV = [
  { label: 'Process', path: '#/process' },
  { label: 'Favorites', path: '#/work' },
  { label: 'Sleeper Picks', path: '#/sleepers' },
  { label: 'About', path: '#/about' },
  { label: 'Contact', path: '#/contact' },
];

function Header({ route }) {
  const [open, setOpen] = useState(false);
  const headerNav = NAV;
  const isActive = (p) => {
    if (p === '#/work') return route === '/work';
    if (p === '#/sleepers') return route === '/sleepers' || route.startsWith('/sleepers/');
    if (p === '#/process') return route === '/process';
    if (p === '#/about') return route === '/about';
    if (p === '#/contact') return route === '/contact';
    return false;
  };
  const navTo = (p) => { setOpen(false); go(p.replace('#', '')); };

  return (
    <header className="sticky top-0 z-50 border-b border-border/60 bg-background/80 backdrop-blur-lg">
      <div className="mx-auto w-full max-w-[1400px] px-5 sm:px-6">
        <div className="flex min-h-16 items-center justify-between gap-5 py-2">
          <button onClick={() => navTo('#/')} className="flex shrink-0 items-center gap-3 transition-opacity hover:opacity-80">
            <LogoImage variant="emblem" alt="FreshWave logo" className="h-11 w-auto" />
            <span className="hidden flex-col leading-none sm:flex">
              <span className="font-heading text-base tracking-[0.12em]">FRESHWAVE</span>
              <span className="mt-1 font-mono text-[9px] uppercase tracking-[0.38em] text-[hsl(var(--vapor-purple))] neon-text-soft">Digital Studio</span>
            </span>
          </button>

          <nav className="ml-8 hidden items-center gap-4 md:flex lg:gap-5 xl:gap-6">
            {headerNav.map((l) => (
              <button
                key={l.path}
                onClick={() => navTo(l.path)}
                className={`font-heading text-xs uppercase tracking-wider transition-colors hover:text-primary ${isActive(l.path) ? 'text-primary' : 'text-muted-foreground'}`}
              >
                {l.label}
              </button>
            ))}
            <Button size="sm" onClick={() => navTo('#/commission')}>Start a piece</Button>
          </nav>

          <button className="flex h-11 w-11 items-center justify-center rounded-md text-foreground hover:bg-muted md:hidden" onClick={() => setOpen(!open)} aria-label="Menu">
            <Icon name={open ? 'close' : 'menu'} className="h-6 w-6" />
          </button>
        </div>
      </div>

      {open && (
        <div className="border-t border-border bg-background/95 px-6 py-6 md:hidden">
          <nav className="flex flex-col gap-1">
            {headerNav.map((l) => (
              <button key={l.path} onClick={() => navTo(l.path)} className="py-3 text-left font-heading text-lg uppercase tracking-wider text-muted-foreground hover:text-primary">
                {l.label}
              </button>
            ))}
            <Button className="mt-4 w-full" onClick={() => navTo('#/commission')}>Start a piece</Button>
          </nav>
        </div>
      )}
    </header>
  );
}

// Footer ------------------------------------------------------------------
function Footer() {
  const connectEmail = FW_CONFIG.contactEmail || 'customerservice@freshwavefinds.shop';
  const socialLinks = ['Instagram', 'TikTok', 'YouTube', 'Makerworld', 'Whatnot', 'Patreon', 'Discord', 'WhatsApp'];

  return (
    <footer className="border-t border-border bg-card text-card-foreground">
      <div className="container mx-auto py-14">
        <div className="grid gap-10 md:grid-cols-3">
          <div className="space-y-4">
            <div className="flex items-center gap-3">
              <LogoImage variant="emblem" alt="FreshWave logo" className="h-14 w-auto" />
              <span className="flex flex-col leading-none">
                <span className="crt-head font-heading text-lg tracking-[0.12em]">FRESHWAVE</span>
                <span className="mt-1 font-mono text-[9px] uppercase tracking-[0.38em] text-[hsl(var(--vapor-purple))] neon-text-soft">Digital Studio</span>
              </span>
            </div>
            <p className="max-w-xs text-sm opacity-80">Design · Print · Create. A studio crafting collectibles that glow in the dark, one layer at a time.</p>
          </div>
          <div className="space-y-4">
            <span className="font-mono text-xs uppercase tracking-[0.25em] opacity-60">Navigate</span>
            <nav className="flex flex-col gap-2">
              {NAV.map((l) => (
                <button key={l.path} onClick={() => go(l.path.replace('#', ''))} className="text-left text-sm transition-colors hover:text-primary">{l.label}</button>
              ))}
            </nav>
          </div>
          <div className="space-y-4">
            <span className="font-mono text-xs uppercase tracking-[0.25em] opacity-60">Connect</span>
            <a href={`mailto:${connectEmail}`} className="block text-sm transition-colors hover:text-primary">{connectEmail}</a>
            <div className="flex flex-wrap gap-x-3 gap-y-2 pt-1 font-mono text-xs uppercase tracking-widest opacity-70">
              {socialLinks.map((label, index) => (
                <React.Fragment key={label}>
                  {index > 0 && <span>·</span>}
                  <a href="#" onClick={(e) => e.preventDefault()} className="hover:text-primary">{label}</a>
                </React.Fragment>
              ))}
            </div>
          </div>
        </div>
        <div className="mt-12 flex flex-col items-center justify-between gap-4 border-t border-border pt-8 sm:flex-row">
          <span className="font-mono text-xs opacity-60">© 2026 FreshWave Digital Studio</span>
          <span className="font-mono text-xs uppercase tracking-[0.25em] opacity-60">FW · MAKER OS · v1.0</span>
        </div>
      </div>
      <div className="grid-floor h-24 opacity-20"></div>
    </footer>
  );
}

// Stats strip -------------------------------------------------------------
function StatsStrip() {
  return (
    <div className="grid grid-cols-1 gap-8 sm:grid-cols-3">
      {STATS.map((s) => (
        <div key={s.label} className="text-center">
          <div className="mb-2 font-display text-4xl text-primary text-glow-cyan neon-text md:text-5xl">{s.value}</div>
          <div className="font-mono text-xs uppercase tracking-[0.25em] text-muted-foreground">{s.label}</div>
        </div>
      ))}
    </div>
  );
}

// Service card ------------------------------------------------------------
function ServiceCard({ s, onOpen }) {
  return (
    <button
      type="button"
      onClick={() => onOpen(s)}
      onPointerDown={triggerButtonSparks}
      className="spark-button card-accent charged-panel group block w-full rounded-2xl border-l-4 bg-card p-8 text-left shadow-lg transition-all duration-300 hover:-translate-y-1 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background"
      style={{ '--card-accent': accentHsl(s.accent), '--panel-accent': accentHsl(s.accent), borderColor: accentHsl(s.accent), boxShadow: `-6px 0 34px -10px ${accentHsl(s.accent, 0.75)}, 0 0 42px ${accentHsl(s.accent, 0.12)}` }}
    >
      <div className="mb-4 flex items-center justify-between gap-4">
        <h3 className="font-heading text-2xl tracking-wide">{s.title}</h3>
        <span className="font-mono text-[10px] uppercase tracking-[0.2em] neon-text-soft" style={{ color: accentHsl(s.accent) }}>{s.tag}</span>
      </div>
      <p className="leading-relaxed text-muted-foreground">{s.description}</p>
      {s.from != null && (
        <div className="mt-5 flex items-baseline gap-2 border-t border-border pt-4">
          <span className="font-mono text-[10px] uppercase tracking-[0.2em] text-muted-foreground">From</span>
          <span className="lit-price quote-data text-2xl neon-text" style={{ color: accentHsl(s.accent) }}>${s.from}</span>
        </div>
      )}
      <span className="mt-5 inline-flex items-center gap-2 font-heading text-[10px] uppercase tracking-wider transition-all group-hover:gap-3" style={{ color: accentHsl(s.accent) }}>
        View details <Icon name="arrow-right" className="h-3.5 w-3.5" />
      </span>
    </button>
  );
}

// Project card ------------------------------------------------------------
function ProjectCard({ project, onOpen }) {
  return (
    <button
      onClick={() => onOpen(project)}
      onPointerDown={triggerButtonSparks}
      className="spark-button card-accent charged-panel group block w-full overflow-hidden rounded-2xl bg-card text-left hover:-translate-y-1"
      style={{ '--card-accent': accentHsl(project.accent), '--panel-accent': accentHsl(project.accent) }}
    >
      <div className="aspect-[4/3] overflow-hidden">
        <Placeholder label={`${project.title} photo`} accent={project.accent} glow className="h-full w-full transition-transform duration-500 group-hover:scale-105" />
      </div>
      <div className="p-6">
        <div className="mb-3 flex items-center justify-between">
          <span className="font-mono text-xs uppercase tracking-[0.2em] neon-text-soft" style={{ color: accentHsl(project.accent) }}>{project.category}</span>
          <span className="font-mono text-xs text-muted-foreground">{project.year}</span>
        </div>
        <h3 className="mb-3 font-heading text-2xl tracking-wide">{project.title}</h3>
        <p className="mb-4 text-sm leading-relaxed text-muted-foreground">{project.description}</p>
        <div className="flex items-center gap-2 font-heading text-xs uppercase tracking-wider text-primary neon-text-soft transition-all group-hover:gap-3">
          View piece <Icon name="arrow-up-right" />
        </div>
      </div>
    </button>
  );
}

// Material swatch ---------------------------------------------------------
function MaterialSwatch({ m }) {
  return (
    <div className="charged-panel group flex items-center gap-4 rounded-xl border border-border bg-card p-4 transition-all hover:-translate-y-0.5" style={{ '--panel-accent': accentHsl(m.accent), borderColor: accentHsl(m.accent, 0.3) }}>
      <span
        className="h-12 w-12 flex-shrink-0 rounded-lg"
        style={{ background: `radial-gradient(circle at 30% 30%, ${accentHsl(m.accent, 0.9)}, ${accentHsl(m.accent, 0.25)})`, boxShadow: `0 0 18px ${accentHsl(m.accent, 0.4)}` }}
      ></span>
      <div>
        <div className="font-heading text-sm tracking-wide">{m.name}</div>
        <div className="text-xs text-muted-foreground">{m.note}</div>
      </div>
    </div>
  );
}

const INQUIRY_ENDPOINT = FW_CONFIG.inquiryEndpoint || 'api/submit-inquiry.php';
const INQUIRY_EMAIL = FW_CONFIG.contactEmail || 'customerservice@freshwavefinds.shop';

function inquirySubject(payload) {
  const kind = payload.kind || 'inquiry';
  const label = kind === 'preload' ? 'Sleeper item request' : kind === 'custom' ? 'Custom request' : 'Contact inquiry';
  return `FreshWave ${label} - ${payload.name || 'New lead'}`;
}

function inquiryBody(payload) {
  const ordered = [
    ['Type', payload.kind],
    ['Name', payload.name],
    ['Email', payload.email],
    ['Project', payload.project],
    ['Sleeper item', payload.preload],
    ['Category', payload.category],
    ['Material', payload.material],
    ['Finish', payload.finish],
    ['Size', payload.size],
    ['Quantity', payload.quantity],
    ['Budget', payload.budget],
    ['Estimate', payload.estimate],
    ['Message', payload.message],
    ['Notes', payload.notes],
  ];
  return ordered
    .filter(([, value]) => value !== undefined && value !== null && String(value).trim() !== '')
    .map(([label, value]) => `${label}: ${value}`)
    .join('\n');
}

function buildInquiryMailto(payload) {
  return `mailto:${INQUIRY_EMAIL}?subject=${encodeURIComponent(inquirySubject(payload))}&body=${encodeURIComponent(inquiryBody(payload))}`;
}

async function submitInquiry(payload) {
  const headers = { 'Content-Type': 'application/json' };
  if (FW_CONFIG.nonce) headers['X-WP-Nonce'] = FW_CONFIG.nonce;
  const response = await fetch(INQUIRY_ENDPOINT, {
    method: 'POST',
    headers,
    body: JSON.stringify({
      source: 'freshwave-site',
      submittedAt: new Date().toISOString(),
      ...payload,
    }),
  });
  const result = await response.json().catch(() => ({}));
  if (!response.ok || !result.ok) {
    throw new Error(result.error || 'Submission failed');
  }
  return result;
}

Object.assign(window, {
  Icon, Button, Placeholder, LogoImage, Eyebrow, Header, Footer, StatsStrip, ServiceCard, ProjectCard, MaterialSwatch,
  TrustStrip, BeforePrintPanel, accentHsl, go, useState, useEffect, useRef, submitInquiry, buildInquiryMailto, fwAsset, triggerButtonSparks,
});
