// parts.jsx — shared UI: Nav, Footer, Pattern overlay, Marquee

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

// ───────────────────────────────────────────────────────────────────
// Pattern overlay — line-art watermark using ArtFace/Hand/Blob
// Density tweakable: off | subtle | regular | strong
// ───────────────────────────────────────────────────────────────────

const PatternBackdrop = ({ density = 'subtle', accent = 'var(--accent)' }) => {
  if (density === 'off') return null;
  const opacity = { subtle: 0.18, regular: 0.30, strong: 0.45 }[density] || 0.18;

  // Static layout — feels intentional, not random
  const items = [
  { x: 4, y: 6, w: 130, r: -8, k: 'face' },
  { x: 78, y: 12, w: 90, r: 14, k: 'hand' },
  { x: 36, y: 28, w: 160, r: 6, k: 'blob' },
  { x: 86, y: 44, w: 110, r: -22, k: 'face' },
  { x: 6, y: 56, w: 140, r: 18, k: 'blob' },
  { x: 62, y: 70, w: 100, r: -6, k: 'hand' },
  { x: 28, y: 86, w: 130, r: 12, k: 'blob' },
  { x: 88, y: 92, w: 90, r: 28, k: 'hand' }];


  return (
    <div className="pointer-events-none absolute inset-0 overflow-hidden" aria-hidden style={{ opacity }}>
      {items.map((it, i) => {
        const Comp = it.k === 'face' ? ArtFace : it.k === 'hand' ? ArtHand : ArtBlob;
        return (
          <div key={i} className="absolute" style={{
            left: it.x + '%', top: it.y + '%', width: it.w, transform: `translate(-50%,-50%) rotate(${it.r}deg)`,
            color: accent
          }}>
            <Comp sw={1.2} />
          </div>);

      })}
    </div>);

};

// ───────────────────────────────────────────────────────────────────
// Wordmark + nav
// ───────────────────────────────────────────────────────────────────

const Wordmark = ({ size = 28, ink = 'var(--ink)' }) =>
<span className="inline-flex items-center select-none" style={{ color: ink }}>
    <img src="Artshtuki_logo.svg" alt="Артштуки" style={{ height: Math.round(size * 1.35), width: 'auto', display: 'block' }} />
  </span>;


const Nav = ({ route, setRoute, copy, onOpenTelegram, scrolled }) => {
  const [mobileOpen, setMobileOpen] = useState(false);

  // Close menu on route change
  useEffect(() => { setMobileOpen(false); }, [route]);

  const link = (key, label) =>
  <button
    onClick={() => setRoute(key)}
    className={`nav-link eyebrow py-2${route === key ? ' nav-active' : ''}`}
    style={{
      color: route === key ? 'var(--ink)' : 'var(--ink-3)',
      fontSize: '13px'
    }}>
      {label}
    </button>;

  const mobileLink = (key, label) =>
  <button
    onClick={() => { setRoute(key); setMobileOpen(false); }}
    className="w-full text-left display py-5 border-b"
    style={{
      fontSize: 'clamp(28px, 7vw, 40px)',
      borderColor: 'var(--hair)',
      fontStyle: route === key ? 'italic' : 'normal',
      color: route === key ? 'var(--ink)' : 'var(--ink-3)',
      fontWeight: 500,
      letterSpacing: '-0.01em',
      lineHeight: 1.05
    }}>
      {label}
    </button>;

  return (
    <>
    <header
      className="fixed top-0 left-0 right-0 z-40"
      style={{
        backdropFilter: 'blur(12px) saturate(140%)',
        WebkitBackdropFilter: 'blur(12px) saturate(140%)',
        background: scrolled || mobileOpen ? 'rgba(252,249,248,.96)' : 'rgba(252,249,248,.55)',
        borderBottom: scrolled || mobileOpen ? '0.5px solid var(--hair)' : '0.5px solid transparent',
        transition: 'all .35s ease'
      }}>

      <div className="max-w-[1320px] mx-auto px-6 md:px-10 h-[72px] flex items-center justify-between">
        <button onClick={() => setRoute('home')} className="flex items-center" aria-label="Артштуки — на главную">
          <Wordmark />
        </button>

        <nav className="hidden md:flex items-center gap-8">
          {link('home', copy.nav.home)}
          {link('gallery', copy.nav.gallery)}
          {link('about', copy.nav.about)}
          {link('order', copy.nav.order)}
        </nav>

        <button
          onClick={onOpenTelegram}
          className="hidden md:inline-flex items-center gap-2 px-4 h-10 rounded-full"
          style={{
            background: 'var(--ink)', color: 'var(--bg)',
            fontFamily: 'PT Sans', fontWeight: 700, letterSpacing: '0.04em', fontSize: "16px"
          }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden>
            <path d="M21.94 4.32 18.5 19.86c-.26 1.16-.95 1.45-1.93.9l-5.32-3.92-2.57 2.47c-.28.28-.52.52-1.07.52l.38-5.42 9.86-8.91c.43-.38-.09-.6-.67-.22L4.99 12.4 0 10.84c-1.08-.34-1.1-1.08.23-1.6L20.6 2.6c.91-.34 1.7.22 1.34 1.72Z" />
          </svg>
          <span>Написать нам</span>
        </button>

        {/* mobile: hamburger + telegram */}
        <div className="md:hidden flex items-center gap-3">
          <button
            onClick={onOpenTelegram}
            className="inline-flex items-center justify-center w-10 h-10 rounded-full"
            style={{ background: 'var(--ink)', color: 'var(--bg)' }}
            aria-label="Telegram">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M21.94 4.32 18.5 19.86c-.26 1.16-.95 1.45-1.93.9l-5.32-3.92-2.57 2.47c-.28.28-.52.52-1.07.52l.38-5.42 9.86-8.91c.43-.38-.09-.6-.67-.22L4.99 12.4 0 10.84c-1.08-.34-1.1-1.08.23-1.6L20.6 2.6c.91-.34 1.7.22 1.34 1.72Z" /></svg>
          </button>
          <button
            onClick={() => setMobileOpen(o => !o)}
            className="inline-flex flex-col items-center justify-center w-10 h-10 gap-[5px]"
            aria-label={mobileOpen ? 'Закрыть меню' : 'Открыть меню'}>
            <span style={{
              display: 'block', width: 22, height: 1.5, background: 'var(--ink)',
              transformOrigin: 'center',
              transform: mobileOpen ? 'translateY(6.5px) rotate(45deg)' : 'none',
              transition: 'transform .3s ease'
            }} />
            <span style={{
              display: 'block', width: 22, height: 1.5, background: 'var(--ink)',
              opacity: mobileOpen ? 0 : 1,
              transition: 'opacity .2s ease'
            }} />
            <span style={{
              display: 'block', width: 22, height: 1.5, background: 'var(--ink)',
              transformOrigin: 'center',
              transform: mobileOpen ? 'translateY(-6.5px) rotate(-45deg)' : 'none',
              transition: 'transform .3s ease'
            }} />
          </button>
        </div>
      </div>

      {/* mobile menu panel */}
      <div
        className="md:hidden overflow-hidden"
        style={{
          maxHeight: mobileOpen ? '400px' : '0',
          transition: 'max-height .4s cubic-bezier(.2,.7,.2,1)',
        }}>
        <nav className="px-6 pt-2 pb-8 flex flex-col">
          {mobileLink('home', copy.nav.home)}
          {mobileLink('gallery', copy.nav.gallery)}
          {mobileLink('about', copy.nav.about)}
          {mobileLink('order', copy.nav.order)}
        </nav>
      </div>

    </header>
    {/* backdrop when menu open */}
    {mobileOpen && <div className="md:hidden fixed inset-0 z-30" onClick={() => setMobileOpen(false)} />}
    </>);
};


// ───────────────────────────────────────────────────────────────────
// Footer
// ───────────────────────────────────────────────────────────────────

const Footer = ({ copy, onOpenTelegram, setRoute }) =>
<footer className="relative mt-32 border-t" style={{ borderColor: 'var(--hair)' }}>
    <div className="max-w-[1320px] mx-auto px-6 md:px-10 py-14">

      {/* Top row: лого + тэглайн слева, соцсети справа */}
      <div className="flex flex-wrap items-end justify-between gap-8 pb-10 border-b" style={{ borderColor: 'var(--hair)' }}>
        <div>
          <Wordmark />
          <p className="mt-5 text-[15px] leading-relaxed max-w-sm" style={{ color: 'var(--ink-3)' }}>
            {copy.tagline}.
          </p>
        </div>
        <div className="flex flex-wrap items-center gap-3">
          <a href="https://t.me/olgashappo" target="_blank" rel="noreferrer" className="ulink eyebrow" style={{ color: 'var(--ink)' }}>TELEGRAM</a>
          <span className="eyebrow opacity-30">·</span>
          <a href="mailto:artshtuki@yandex.ru" target="_blank" rel="noreferrer" className="ulink eyebrow" style={{ color: 'var(--ink)' }}>ARTSHTUKI@YANDEX.RU</a>
          <span className="eyebrow opacity-30">·</span>
          <a href="https://vk.com/artshtukishop" target="_blank" rel="noreferrer" className="ulink eyebrow" style={{ color: 'var(--ink)' }}>ВКОНТАКТЕ</a>
        </div>
      </div>

      {/* Bottom row: копирайт + сделано руками */}
      <div className="mt-6 flex flex-wrap items-center justify-between gap-4">
        <div className="eyebrow opacity-55">{copy.footer.rights}</div>
        <div className="eyebrow opacity-55">СДЕЛАНО РУКАМИ</div>
      </div>

    </div>
  </footer>;


// ───────────────────────────────────────────────────────────────────
// Telegram modal
// ───────────────────────────────────────────────────────────────────

const TelegramModal = ({ open, onClose, copy, productTitle }) => {
  if (!open) return null;
  return (
    <div className="fixed inset-0 z-[60] flex items-center justify-center fade-in" style={{ background: 'rgba(17,24,28,.32)' }}>
      <button className="absolute inset-0" onClick={onClose} aria-label="закрыть" />
      <div className="relative w-[min(440px,92vw)] rounded-2xl p-8" style={{ background: 'var(--bg)', border: '0.5px solid var(--hair-2)', boxShadow: '0 20px 60px rgba(17,24,28,.16)', margin: "0px" }}>
        <button onClick={onClose} className="absolute top-4 right-4 w-8 h-8 rounded-full flex items-center justify-center" style={{ color: 'var(--ink-3)', fontSize: "50px", fontWeight: "100", lineHeight: "0.4" }} aria-label="закрыть">×</button>
        <h3 className="display text-[34px] leading-[1] mb-3">Напишите нам</h3>
        <p className="text-[15px] leading-relaxed mb-6" style={{ color: 'var(--ink-3)', fontSize: "18px", lineHeight: "1.63" }}>
          {productTitle ?
          <>Ответим в течение дня. Расскажите, что вас зацепило: <span className="italic" style={{ color: 'var(--ink)' }}>«{productTitle}»</span> — и любые вопросы.</> :
          <>Ответим в течение дня. Расскажите, что ищете — подскажем и пришлём фото.</>}
        </p>
        <a href="https://t.me/olgashappo" target="_blank" rel="noreferrer" className="block w-full text-center py-3 rounded-full" style={{ background: 'var(--ink)', color: 'var(--bg)', fontFamily: 'PT Sans', fontWeight: 700, letterSpacing: '0.04em' }}>Написать в Telegram</a>
        <a href="mailto:artshtuki@yandex.ru" target="_blank" rel="noreferrer" className="block w-full text-center py-3 mt-2 rounded-full" style={{ border: '0.5px solid var(--hair-2)', color: 'var(--ink)', fontFamily: 'PT Sans', fontWeight: 700, letterSpacing: '0.04em' }}>Написать на почту</a>
        <a href="https://vk.com/im/convo/-109863720?entrypoint=community_page&tab=all" target="_blank" rel="noreferrer" className="block w-full text-center py-3 mt-2 rounded-full" style={{ border: '0.5px solid var(--hair-2)', color: 'var(--ink)', fontFamily: 'PT Sans', fontWeight: 700, letterSpacing: '0.04em' }}>Написать во ВКонтакте</a>
        
      </div>
    </div>);

};

// ───────────────────────────────────────────────────────────────────
// Marquee
// ───────────────────────────────────────────────────────────────────

const Marquee = ({ lang }) => {
  const items = lang === 'ru' ?
  ['Сделано руками', 'Один экземпляр', 'Москва', 'С 2019 года', 'Тёплая керамика', 'Лён, орех, бумага', 'Без серий, без склада'] :
  ['Made by hand', 'One of one', 'Moscow', 'Since 2019', 'Warm ceramics', 'Linen, walnut, paper', 'No series, no warehouse'];
  const sequence = [...items, ...items, ...items, ...items];

  return (
    <div className="relative py-7 overflow-hidden border-y" style={{ borderColor: 'var(--hair)', background: 'var(--linen)' }}>
      <div className="flex marquee-track gap-12 whitespace-nowrap will-change-transform">
        {sequence.map((s, i) =>
        <span key={i} className="display text-[42px] md:text-[64px] tracking-tight" style={{ color: 'var(--ink)', fontStyle: 'italic', fontWeight: 500 }}>
            {s} <span className="not-italic mx-6" style={{ color: 'var(--clay)' }}>✿</span>
          </span>
        )}
      </div>
    </div>);

};

// ───────────────────────────────────────────────────────────────────
// Product card
// ───────────────────────────────────────────────────────────────────

const ProductCard = ({ p, lang, onOpen, copy, layout = 'grid' }) => {
  const t = COPY[lang].product;
  const aspect = layout === 'masonry' ?
  p.id.charCodeAt(2) % 3 === 0 ? '3/4' : p.id.charCodeAt(2) % 3 === 1 ? '4/5' : '1/1' :
  '4/5';
  const coverImg = p.imgs && p.imgs[0];
  return (
    <a href={'product-' + p.id + '.html'} className="pc text-left group block w-full">
      <div className="relative overflow-hidden">
        {coverImg
          ? <div style={{ aspectRatio: aspect, overflow: 'hidden' }}>
              <img src={coverImg} alt={p.title[lang]} style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block', transition: 'transform .4s ease' }} className="group-hover:scale-[1.03]" />
            </div>
          : <ProductPlaceholder tone={p.tone} form={p.form} ratio={aspect} label={p.subtitle[lang]} />
        }
        <div className="pc-overlay absolute inset-0 flex items-end p-4" style={{ background: 'linear-gradient(180deg, rgba(17,24,28,0) 50%, rgba(17,24,28,.32) 100%)' }}>
          <span className="eyebrow text-[11px]" style={{ color: 'var(--bg)' }}>Смотреть →</span>
        </div>
      </div>
      <div className="mt-4 flex items-baseline justify-between gap-4">
        <div className="min-w-0">
          <div className="display text-[20px] leading-tight truncate">{p.title[lang]}</div>
          <div className="mt-0.5" style={{ color: 'var(--ink-3)', fontSize: '15px' }}>{p.subtitle[lang]}</div>
        </div>
        <div className="font-sans font-bold text-[14px] tabular-nums whitespace-nowrap" style={{ color: 'var(--ink)' }}>
          {p.price ? p.price.toLocaleString('ru-RU') + ' ₽' : '—'}
        </div>
      </div>
    </a>);
};

Object.assign(window, {
  PatternBackdrop, Wordmark, Nav, Footer, TelegramModal, Marquee, ProductCard
});