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

// ─────────────── DATA ───────────────
const BRANDS = [
  {
    id: 'royal-essence',
    num: '01',
    name: 'Royal Essence',
    tagline: 'Crystal candles, jewellery & home rituals.',
    category: 'Lifestyle / Home',
    location: 'Gold Coast, AU',
    href: 'https://www.royalessence.com.au',
    logo: 'assets/royal-essence-logo.svg',
  },
  {
    id: 'zoey',
    num: '02',
    name: 'Zöey',
    tagline: 'Modern beauty essentials for the everyday.',
    category: 'Beauty',
    location: 'Manila, PH',
    href: 'https://zoey.ph',
    logo: 'assets/zoey-logo.png',
  },
  {
    id: 'idol',
    num: '03',
    name: 'Idol',
    tagline: 'Beauty for the next generation.',
    category: 'Beauty',
    location: 'Manila, PH',
    href: 'https://idol.ph',
    logo: 'assets/idol-logo.svg',
  },
];

const DEFAULTS = /*EDITMODE-BEGIN*/{
  "mode": "light",
  "motion": "moderate",
  "bg": "sunset",
  "headlineA": "A house of",
  "headlineB": "brands.",
  "tagline": "Kaizen Brands curates and grows distinctive consumer brands across beauty, wellness, and lifestyle — built with care, designed to endure."
}/*EDITMODE-END*/;

// ─────────────── UTILS ───────────────
function useReveal() {
  const ref = useRef(null);
  useEffect(() => {
    if (!ref.current) return;
    const enable = () => {
      document.documentElement.classList.add('reveals-on');
      const targets = ref.current.querySelectorAll('.reveal');
      const io = new IntersectionObserver((entries) => {
        entries.forEach(en => { if (en.isIntersecting) en.target.classList.add('is-in'); });
      }, { threshold: 0.12, rootMargin: '0px 0px -8% 0px' });
      targets.forEach(t => io.observe(t));
      return io;
    };
    let io;
    if (document.visibilityState === 'visible') {
      io = enable();
    } else {
      const onVis = () => {
        if (document.visibilityState === 'visible') {
          document.removeEventListener('visibilitychange', onVis);
          io = enable();
        }
      };
      document.addEventListener('visibilitychange', onVis);
      return () => { document.removeEventListener('visibilitychange', onVis); if (io) io.disconnect(); };
    }
    return () => io && io.disconnect();
  }, []);
  return ref;
}

function useClock() {
  const [t, setT] = useState(new Date());
  useEffect(() => {
    const i = setInterval(() => setT(new Date()), 1000);
    return () => clearInterval(i);
  }, []);
  return t;
}

function fmtTime(d, tz) {
  try {
    return d.toLocaleTimeString('en-US', { hour12: false, timeZone: tz, hour: '2-digit', minute: '2-digit' });
  } catch { return d.toLocaleTimeString().slice(0,5); }
}

// ─────────────── DECORATIVE SHAPES ───────────────
const StarBurst = ({ className }) => (
  <svg viewBox="0 0 100 100" className={className} fill="none">
    <path d="M50 0 L58 38 L96 30 L66 56 L94 86 L56 76 L50 100 L44 76 L6 86 L34 56 L4 30 L42 38 Z" fill="currentColor" />
  </svg>
);

const Arrow = ({ className }) => (
  <svg viewBox="0 0 140 60" className={className} fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
    <path d="M6 30 H 122" />
    <path d="M96 8 L 130 30 L 96 52" />
    <path d="M16 18 H 30" opacity="0.5" />
    <path d="M16 42 H 30" opacity="0.5" />
  </svg>
);

const StampBadge = ({ className }) => (
  <svg viewBox="0 0 120 120" className={className} fill="none">
    <circle cx="60" cy="60" r="56" stroke="currentColor" strokeWidth="2.5" strokeDasharray="2 5" />
    <circle cx="60" cy="60" r="32" stroke="currentColor" strokeWidth="2" fill="none" />
    <text x="60" y="56" fontFamily="Bowlby One, sans-serif" fontSize="13" fill="currentColor" textAnchor="middle">KAIZEN</text>
    <text x="60" y="72" fontFamily="Bowlby One, sans-serif" fontSize="11" fill="currentColor" textAnchor="middle">BRANDS</text>
    <text x="60" y="90" fontFamily="Space Mono, monospace" fontSize="7" fill="currentColor" textAnchor="middle" letterSpacing="2">EST 2016</text>
  </svg>
);

// ─────────────── CURSOR ───────────────
function Cursor() {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    let raf, tx = 0, ty = 0, x = 0, y = 0;
    const onMove = (e) => { tx = e.clientX; ty = e.clientY; el.classList.add('ready'); };
    const onOver = (e) => {
      const t = e.target;
      if (t.closest && t.closest('a, button, .brand, .cta-btn, .nav-end .dot, .marquee, .brand-pill')) el.classList.add('big');
      else el.classList.remove('big');
    };
    const onLeave = () => el.classList.remove('ready');
    const loop = () => {
      x += (tx - x) * 0.2;
      y += (ty - y) * 0.2;
      el.style.transform = `translate(${x}px, ${y}px) translate(-50%, -50%)`;
      raf = requestAnimationFrame(loop);
    };
    window.addEventListener('mousemove', onMove);
    window.addEventListener('mouseover', onOver);
    document.addEventListener('mouseleave', onLeave);
    loop();
    return () => {
      cancelAnimationFrame(raf);
      window.removeEventListener('mousemove', onMove);
      window.removeEventListener('mouseover', onOver);
      document.removeEventListener('mouseleave', onLeave);
    };
  }, []);
  return <div className="cursor" ref={ref} aria-hidden="true" />;
}

// ─────────────── NAV ───────────────
function Nav() {
  const t = useClock();
  return (
    <nav className="nav">
      <a className="nav-mark" href="#top">
        <span className="kb-glyph">K</span>
        <span className="wm">Kaizen Brands</span>
      </a>
      <div className="nav-mid">
        <span className="mono uc">Index</span>
        <span className="pip" />
        <span className="mono uc">Two cities</span>
        <span className="pip" />
        <span className="mono uc">Three brands</span>
        <span className="pip" />
        <span className="mono uc">MMXXVI</span>
      </div>
      <div className="nav-end">
        <span className="mono nav-clock">MNL {fmtTime(t, 'Asia/Manila')}</span>
        <span className="mono nav-clock" style={{ color: 'var(--ink-3)' }}>GC {fmtTime(t, 'Australia/Brisbane')}</span>
        <span className="dot" />
      </div>
    </nav>
  );
}

// ─────────────── HERO ───────────────
function Hero({ headlineA, headlineB, tagline }) {
  const titleRef = useRef(null);
  useEffect(() => {
    const trigger = () => requestAnimationFrame(() => titleRef.current && titleRef.current.classList.add('in'));
    if (document.visibilityState === 'visible') {
      trigger();
    } else {
      const onVis = () => {
        if (document.visibilityState === 'visible') {
          document.removeEventListener('visibilitychange', onVis);
          trigger();
        }
      };
      document.addEventListener('visibilitychange', onVis);
      return () => document.removeEventListener('visibilitychange', onVis);
    }
  }, [headlineA, headlineB]);

  const wrapWords = (s, offset = 0) => s.split(' ').map((w, i) => (
    <span className="word" key={`${offset}-${i}`} style={{ animationDelay: `${0.06 + (i + offset) * 0.09}s` }}>
      {w}{' '}
    </span>
  ));

  const aWords = headlineA.split(' ');
  const lineALen = aWords.length;

  return (
    <header className="hero shell" id="top">
      {/* Decorative shapes */}
      <StarBurst className="deco deco-star-1 spin" />
      <StarBurst className="deco deco-star-2 float" />
      <Arrow className="deco deco-arrow-1 float2" />
      <Arrow className="deco deco-arrow-2 float" />
      <StampBadge className="deco deco-stamp spin" />

      <div className="hero-top">
        <div className="col">
          <span className="mono uc label">Vol. 01 / Index</span>
          <span className="mono uc">A portfolio</span>
        </div>
        <div className="col">
          <span className="mono uc label">Est.</span>
          <span className="mono uc">2016 — Present</span>
        </div>
        <div className="col right">
          <span className="mono uc label">Pages</span>
          <span className="mono uc">01 / 04</span>
        </div>
      </div>

      <h1 ref={titleRef} className="display hero-title" aria-label={`${headlineA} ${headlineB}`}>
        <span className="row">{wrapWords(headlineA, 0)}</span>
        <span className="row">
          <span className="word" style={{ animationDelay: `${0.06 + lineALen * 0.09}s` }}>
            <span className="brand-pill">
              <span className="num">3</span>
              <span>BRANDS.</span>
            </span>
          </span>
        </span>
      </h1>

      <div className="hero-bot">
        <p className="desc">{tagline}</p>
        <div />
        <div className="scroll">
          <span className="mono uc">Scroll</span>
          <span className="scroll-line" />
          <span className="mono uc">Index</span>
        </div>
      </div>
    </header>
  );
}

// ─────────────── MARQUEE ───────────────
function Marquee({ red = false }) {
  const items = ['Royal Essence', 'Zöey', 'Idol'];
  const loop = Array.from({ length: 4 }, () => items).flat();
  return (
    <div className={`marquee ${red ? 'red' : ''}`} aria-hidden="true">
      <div className="marquee-track">
        {[...loop, ...loop].map((w, i) => (
          <div className="marquee-item" key={i}>
            <span>{w}</span>
            <span className="marquee-glyph">✺</span>
          </div>
        ))}
      </div>
    </div>
  );
}

// ─────────────── PORTFOLIO ───────────────
function BrandRow({ brand }) {
  return (
    <a className="brand reveal" href={brand.href} target="_blank" rel="noopener noreferrer" data-brand={brand.id}>
      <div className="brand-num display">{brand.num}</div>
      <div className="brand-id">
        <div className="brand-name display">{brand.name}</div>
        <div className="brand-logo-wrap">
          <img src={brand.logo} alt={`${brand.name} logo`} />
        </div>
      </div>
      <div className="brand-meta">
        <span className="tag mono uc">{brand.category} · {brand.location}</span>
        <span className="brand-tagline">{brand.tagline}</span>
      </div>
      <div className="brand-visit">
        <span className="label mono uc">Visit</span>
        <span className="arrow" aria-hidden="true">
          <svg width="18" height="18" viewBox="0 0 16 16" fill="none">
            <path d="M3 13L13 3M13 3H5M13 3V11" stroke="currentColor" strokeWidth="1.8" strokeLinecap="square" />
          </svg>
        </span>
      </div>
    </a>
  );
}

function Portfolio() {
  return (
    <section className="block shell" id="portfolio">
      <div className="sec-head reveal">
        <span className="ix mono uc">§ 02</span>
        <h2 className="ti">The <span className="red">brands.</span></h2>
        <span className="meta mono uc">Three of three</span>
      </div>
      <div className="brands">
        {BRANDS.map(b => <BrandRow key={b.id} brand={b} />)}
      </div>
    </section>
  );
}

// ─────────────── ABOUT ───────────────
function About() {
  return (
    <section className="block shell" id="about">
      <div className="sec-head reveal">
        <span className="ix mono uc">§ 03</span>
        <h2 className="ti">Our <span className="red">philosophy.</span></h2>
        <span className="meta mono uc">Kaizen / 改善</span>
      </div>

      <div className="about">
        <p className="about-text reveal">
          We build brands the way good things are built — <span className="red">slowly, with care.</span>
        </p>

        <div className="about-grid">
          <div className="cell reveal d2">
            <span className="k mono uc">Discipline</span>
            <span className="v">Kaizen <span className="red">改善</span></span>
            <p>Continuous, deliberate improvement. Small steps, compounded over years.</p>
          </div>
          <div className="cell reveal d2">
            <span className="k mono uc">Footprint</span>
            <span className="v">Manila <span className="red">⇄</span> Gold Coast</span>
            <p>Two cities, one team. Shipping to customers around the world.</p>
          </div>
          <div className="cell reveal d3">
            <span className="k mono uc">Categories</span>
            <span className="v">Beauty, <span className="red">home,</span> wellness</span>
            <p>We invest where craft, ritual, and daily use meet.</p>
          </div>
          <div className="cell reveal d3">
            <span className="k mono uc">Since</span>
            <span className="v">2016<span className="red">.</span></span>
            <p>Independent. Operator-led. Built for the next decade.</p>
          </div>
        </div>
      </div>

      <div className="cta reveal d4">
        <div className="cta-head">Got a brand <span className="red">we should know about?</span></div>
        <a className="cta-btn" href="contact.html">
          Say hello
          <svg width="20" height="20" viewBox="0 0 16 16" fill="none">
            <path d="M3 13L13 3M13 3H5M13 3V11" stroke="currentColor" strokeWidth="1.8" strokeLinecap="square" />
          </svg>
        </a>
      </div>
    </section>
  );
}

// ─────────────── FOOTER ───────────────
function Footer() {
  return (
    <footer className="foot shell">
      <span className="mono uc">© Kaizen Brands · MMXXVI</span>
      <div className="links">
        <a className="mono uc" href="privacy.html">Privacy</a>
        <a className="mono uc" href="contact.html">Contact</a>
        <a className="mono uc" href="mailto:hello@kaizenbrands.com">hello@kaizenbrands.com</a>
      </div>
      <span className="mono uc end">kaizenbrands.com</span>
    </footer>
  );
}

// ─────────────── TWEAKS ───────────────
function KBTweaks({ t, setTweak }) {
  if (typeof window.TweaksPanel === 'undefined') return null;
  const { TweaksPanel, TweakSection, TweakRadio, TweakText } = window;
  return (
    <TweaksPanel title="Tweaks">
      <TweakSection label="Mode" />
      <TweakRadio label="Theme" value={t.mode} options={['light', 'dark']}
        onChange={(v) => setTweak('mode', v)} />
      <TweakSection label="Background" />
      <TweakRadio label="Style" value={t.bg} options={['sunset', 'fire', 'solid']}
        onChange={(v) => setTweak('bg', v)} />
      <TweakSection label="Motion" />
      <TweakRadio label="Intensity" value={t.motion}
        options={['subtle', 'moderate', 'bold']}
        onChange={(v) => setTweak('motion', v)} />
      <TweakSection label="Headline" />
      <TweakText label="Line 1" value={t.headlineA} onChange={(v) => setTweak('headlineA', v)} />
      <TweakText label="Line 2" value={t.headlineB} onChange={(v) => setTweak('headlineB', v)} />
      <TweakSection label="Tagline" />
      <TweakText label="Copy" value={t.tagline} onChange={(v) => setTweak('tagline', v)} />
    </TweaksPanel>
  );
}

// ─────────────── APP ───────────────
function App() {
  const [t, setTweak] = window.useTweaks(DEFAULTS);
  const revealRef = useReveal();

  useEffect(() => {
    const r = document.documentElement;
    r.setAttribute('data-mode', t.mode);
    r.setAttribute('data-motion', t.motion);
    r.setAttribute('data-bg', t.bg);
  }, [t.mode, t.motion, t.bg]);

  return (
    <div ref={revealRef}>
      <Cursor />
      <Nav />
      <Hero headlineA={t.headlineA} headlineB={t.headlineB} tagline={t.tagline} />
      <Marquee />
      <Portfolio />
      <Marquee red />
      <About />
      <Footer />
      <KBTweaks t={t} setTweak={setTweak} />
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
