// Pet MBTI — shared UI. Exports: PawIcon, Sparkle, Cloud, AppIcon, NavBar, Footer, Btn, TraitBar, TypeThumb, AppStoreBadge, AppQR

const C = window.PM_C;
const S = window.PM_STR;

// Real Paws app icon (resized from the shipping iOS icon). Paths are root-relative;
// per-type pages under /t/ set <base href="/"> so this resolves everywhere.
const APP_ICON = 'assets/app-icon.png';

// ── little vector marks (no emoji, no black stroke) ──
function PawIcon({ size = 24, color = C.paw, style, className }) {
  return (
    <svg width={size} height={size} viewBox="0 0 32 32" fill={color} style={style} className={className} aria-hidden="true">
      <ellipse cx="16" cy="21" rx="7" ry="6" />
      <ellipse cx="8"  cy="12" rx="3" ry="3.6" />
      <ellipse cx="16" cy="9"  rx="3.1" ry="3.8" />
      <ellipse cx="24" cy="12" rx="3" ry="3.6" />
    </svg>
  );
}
function Sparkle({ size = 20, color = C.paw, style, className }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill={color} style={style} className={className} aria-hidden="true">
      <path d="M12 0c.7 6 3.3 8.6 12 12-8.7 3.4-11.3 6-12 12-.7-6-3.3-8.6-12-12C8.7 8.6 11.3 6 12 0Z" />
    </svg>
  );
}
function Cloud({ w = 90, color = '#fff', style }) {
  return (
    <svg width={w} height={w * 0.42} viewBox="0 0 100 42" fill={color} style={style} aria-hidden="true">
      <ellipse cx="30" cy="28" rx="24" ry="14" />
      <ellipse cx="55" cy="22" rx="22" ry="18" />
      <ellipse cx="76" cy="30" rx="18" ry="12" />
      <rect x="18" y="30" width="66" height="12" rx="6" />
    </svg>
  );
}

// Real app-icon tile, used for the brand mark and app-download bands.
function AppIcon({ size = 38, radius = 13, shadow = true }) {
  return (
    <img src={APP_ICON} alt="Paws — pet diary app icon" width={size} height={size}
      style={{ width: size, height: size, borderRadius: radius, display: 'block', objectFit: 'cover',
        flexShrink: 0, boxShadow: shadow ? `0 4px 12px ${C.paw}55` : 'none' }} />
  );
}

// ── buttons ──
function Btn({ children, onClick, kind = 'primary', color = C.pawDeep, size = 'md', style, disabled }) {
  const pads = size === 'lg' ? '17px 34px' : size === 'sm' ? '9px 18px' : '13px 26px';
  const fs = size === 'lg' ? 20 : size === 'sm' ? 14 : 16;
  const base = {
    fontFamily: "'Fredoka', sans-serif", fontWeight: 600, fontSize: fs, cursor: disabled ? 'default' : 'pointer',
    border: 'none', borderRadius: 999, padding: pads, letterSpacing: '.2px',
    transition: 'transform .15s ease, box-shadow .15s ease, background .15s ease',
    display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 9, opacity: disabled ? .5 : 1,
    whiteSpace: 'nowrap',
  };
  const kinds = {
    primary: { background: color, color: '#fff', boxShadow: `0 8px 20px ${color}44` },
    soft:    { background: C.panel, color: C.ink, boxShadow: '0 3px 12px rgba(168,107,52,0.10)' },
    ghost:   { background: 'transparent', color: C.ink2, boxShadow: 'none' },
  };
  return (
    <button className="pm-btn" onClick={disabled ? undefined : onClick} disabled={disabled}
      style={{ ...base, ...kinds[kind], ...style }}>{children}</button>
  );
}

// ── language switcher (top-right). Each menu item is a hard <a> navigation to the
// mirrored page in that language's static shell tree — a real page load is what
// swaps in the localized <head>. Root-absolute hrefs (pmLangHref) so they are
// immune to <base href="/"> and stay crawlable (hreflang counterparts). Driven off
// PM_LANGS, so it grows automatically as languages are added. ──
function LangSwitch() {
  const [open, setOpen] = React.useState(false);
  const wrapRef = React.useRef(null);
  const langs = window.PM_LANGS;
  const current = langs.find((l) => l.code === window.PM_LANG) || langs[0];

  // Close on outside click / Escape.
  React.useEffect(() => {
    if (!open) return;
    const onDoc = (e) => { if (wrapRef.current && !wrapRef.current.contains(e.target)) setOpen(false); };
    const onKey = (e) => { if (e.key === 'Escape') setOpen(false); };
    document.addEventListener('mousedown', onDoc);
    document.addEventListener('keydown', onKey);
    return () => { document.removeEventListener('mousedown', onDoc); document.removeEventListener('keydown', onKey); };
  }, [open]);

  return (
    <div ref={wrapRef} style={{ position: 'relative' }}>
      <button className="pm-navlink" onClick={() => setOpen((v) => !v)} aria-haspopup="menu"
        aria-expanded={open} aria-label={S.langMenuLabel} style={{
          display: 'inline-flex', alignItems: 'center', gap: 6, border: `1px solid ${C.line}`,
          background: C.panel, cursor: 'pointer', fontFamily: "'Nunito', sans-serif", fontWeight: 800,
          fontSize: 14, color: C.ink2, padding: '7px 13px', borderRadius: 999, whiteSpace: 'nowrap' }}>
        <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke={C.muted} strokeWidth="2"
          strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
          <circle cx="12" cy="12" r="10" /><path d="M2 12h20" />
          <path d="M12 2a15.3 15.3 0 0 1 0 20 15.3 15.3 0 0 1 0-20z" />
        </svg>
        <span className="pm-langlabel">{current.label}</span>
        <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke={C.muted} strokeWidth="2.5"
          strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"
          style={{ transform: open ? 'rotate(180deg)' : 'none', transition: 'transform .18s ease' }}>
          <path d="M6 9l6 6 6-6" />
        </svg>
      </button>
      {open && (
        <div role="menu" style={{
          position: 'absolute', top: 'calc(100% + 8px)', left: '50%', transform: 'translateX(-50%)', minWidth: 148, zIndex: 60,
          background: C.panel, border: `1px solid ${C.line}`, borderRadius: 16, padding: 6,
          boxShadow: '0 12px 30px rgba(168,107,52,0.18)' }}>
          {langs.map((l) => {
            const active = l.code === current.code;
            return (
              <a key={l.code} href={window.pmLangHref(l.code)} hrefLang={l.hrefLang} role="menuitem"
                lang={l.code} className="pm-navlink" aria-current={active ? 'true' : undefined}
                style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10,
                  padding: '9px 12px', borderRadius: 11, fontFamily: "'Nunito', sans-serif",
                  fontWeight: active ? 900 : 700, fontSize: 15,
                  color: active ? C.ink : C.ink2, background: active ? C.panelAlt : 'transparent' }}>
                {l.label}
                {active && (
                  <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke={C.paw} strokeWidth="3"
                    strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M20 6L9 17l-5-5" /></svg>
                )}
              </a>
            );
          })}
        </div>
      )}
    </div>
  );
}

// ── top nav ──
function NavBar({ onHome, onTypes, onStart, active }) {
  return (
    <header style={{
      position: 'sticky', top: 0, zIndex: 50, background: 'rgba(251,227,202,0.82)',
      backdropFilter: 'blur(10px)', borderBottom: `1px solid ${C.line}`,
    }}>
      <div className="pm-nav-inner" style={{ maxWidth: 1160, margin: '0 auto', padding: '0 28px', height: 68,
        display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <button onClick={onHome} aria-label="Paws home" style={{ border: 'none', background: 'none', cursor: 'pointer',
          display: 'flex', alignItems: 'center', gap: 10, padding: 0 }}>
          <AppIcon size={38} radius={12} />
          <span style={{ fontFamily: "'Fredoka', sans-serif", fontWeight: 600, fontSize: 23, color: C.ink }}>Paws</span>
          <span className="pm-brandtag" style={{ fontFamily: "'Nunito', sans-serif", fontWeight: 700, fontSize: 13, color: C.muted, marginTop: 4 }}>{S.brandTag}</span>
        </button>
        <nav style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <button onClick={onTypes} className="pm-navlink pm-nav-types" style={{
            border: 'none', background: 'none', cursor: 'pointer', fontFamily: "'Nunito', sans-serif",
            fontWeight: 800, fontSize: 15, color: active === 'types' ? C.ink : C.ink2, padding: '8px 14px', borderRadius: 999, whiteSpace: 'nowrap' }}>
            {S.nav.types}
          </button>
          <LangSwitch />
          <Btn size="sm" onClick={onStart} color={C.pawDeep}>{S.nav.take}</Btn>
        </nav>
      </div>
    </header>
  );
}

// ── Apple mark + App Store badge ──
const APP_URL = 'https://apps.apple.com/us/app/paws-pet-diary/id6770104992';

function AppleMark({ size = 22, color = '#fff' }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill={color} aria-hidden="true">
      <path d="M17.05 12.54c-.03-2.6 2.12-3.85 2.22-3.91-1.21-1.77-3.09-2.02-3.76-2.05-1.6-.16-3.12.94-3.93.94-.81 0-2.06-.92-3.39-.9-1.74.03-3.35 1.01-4.25 2.57-1.81 3.14-.46 7.79 1.3 10.34.86 1.25 1.88 2.65 3.22 2.6 1.29-.05 1.78-.83 3.34-.83 1.56 0 2 .83 3.37.81 1.39-.03 2.27-1.27 3.12-2.53.98-1.45 1.39-2.85 1.41-2.92-.03-.01-2.71-1.04-2.74-4.13zM14.6 4.83c.71-.86 1.19-2.06 1.06-3.25-1.02.04-2.26.68-2.99 1.54-.66.76-1.23 1.98-1.08 3.15 1.14.09 2.3-.58 3.01-1.44z" />
    </svg>
  );
}

function AppStoreBadge() {
  return (
    <a href={APP_URL} target="_blank" rel="noopener noreferrer" className="pm-btn" style={{
      display: 'inline-flex', alignItems: 'center', gap: 12, background: C.ink, color: '#fff',
      borderRadius: 16, padding: '11px 20px 11px 18px', textDecoration: 'none',
      boxShadow: '0 8px 20px rgba(58,49,40,0.22)', transition: 'transform .15s ease, box-shadow .15s ease' }}>
      <AppleMark size={30} color="#fff" />
      <span style={{ lineHeight: 1.1, textAlign: 'left' }}>
        <span style={{ display: 'block', fontFamily: "'Nunito', sans-serif", fontWeight: 700, fontSize: 11.5, opacity: .85, letterSpacing: '.3px' }}>Download on the</span>
        <span style={{ display: 'block', fontFamily: "'Fredoka', sans-serif", fontWeight: 600, fontSize: 19 }}>App Store</span>
      </span>
    </a>
  );
}

// QR code linking to the app (renders via qrcode-generator, falls back gracefully)
function AppQR({ size = 96, caption = S.qrCaption }) {
  const src = React.useMemo(() => {
    try {
      if (typeof qrcode === 'undefined') return null;
      const qr = qrcode(0, 'M');
      qr.addData(APP_URL);
      qr.make();
      return qr.createDataURL(6, 8);
    } catch (e) { return null; }
  }, []);
  if (!src) return null;
  return (
    <a href={APP_URL} target="_blank" rel="noopener noreferrer" style={{
      display: 'inline-flex', flexDirection: 'column', alignItems: 'center', gap: 7, textDecoration: 'none' }}>
      <span style={{ background: '#fff', borderRadius: 14, padding: 8, boxShadow: '0 4px 14px rgba(58,49,40,0.14)', lineHeight: 0 }}>
        <img src={src} alt="QR code to download Paws on the App Store" width={size} height={size}
          style={{ display: 'block', width: size, height: size, imageRendering: 'pixelated', borderRadius: 4 }} />
      </span>
      {caption && <span style={{ fontFamily: "'Nunito', sans-serif", fontWeight: 800, fontSize: 11.5, color: C.muted, letterSpacing: '.2px' }}>{caption}</span>}
    </a>
  );
}

// ── footer ──
function Footer() {
  return (
    <footer style={{ marginTop: 0, background: C.bgWarm, borderTop: `1px solid ${C.line}` }}>
      {/* app download band */}
      <div>
        <div style={{ maxWidth: 1160, margin: '0 auto', padding: '36px 28px',
          display: 'flex', flexWrap: 'wrap', gap: 24, alignItems: 'center', justifyContent: 'space-between' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
            <AppIcon size={56} radius={16} />
            <div style={{ lineHeight: 1.2 }}>
              <div style={{ fontFamily: "'Fredoka', sans-serif", fontWeight: 600, fontSize: 'clamp(20px, 2.6vw, 26px)', color: C.ink }}>{S.footerTitle}</div>
              <div style={{ fontFamily: "'Nunito', sans-serif", fontWeight: 700, fontSize: 15, color: C.ink2, marginTop: 3, maxWidth: 440, textWrap: 'pretty' }}>
                {S.footerBody}
              </div>
            </div>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 20, flexWrap: 'wrap' }}>
            <AppStoreBadge />
            <AppQR size={92} />
          </div>
        </div>
      </div>
    </footer>
  );
}

// ── trait bar (result page) ──
function TraitBar({ axis, pct, colors }) {
  const winnerB = axis._winner === axis.b.k;
  const side = winnerB ? axis.b : axis.a;
  const other = winnerB ? axis.a : axis.b;
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 7 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
        <span style={{ fontFamily: "'Nunito', sans-serif", fontWeight: 800, fontSize: 13, color: C.muted, textTransform: 'uppercase', letterSpacing: '.5px' }}>{axis.label}</span>
        <span style={{ fontFamily: "'Fredoka', sans-serif", fontWeight: 600, fontSize: 15, color: colors.ink }}>
          {side.name} <span style={{ color: C.muted, fontSize: 13 }}>{pct}%</span>
        </span>
      </div>
      <div style={{ position: 'relative', height: 12, borderRadius: 999, background: C.line, overflow: 'hidden' }}>
        <div style={{ position: 'absolute', top: 0, bottom: 0, left: 0, width: pct + '%',
          borderRadius: 999, background: `linear-gradient(90deg, ${colors.mid}, ${colors.deep})` }} />
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', fontFamily: "'Nunito', sans-serif", fontWeight: 700, fontSize: 12, color: C.muted }}>
        <span style={{ color: winnerB ? C.muted : colors.ink }}>{other.name}</span>
        <span style={{ color: winnerB ? colors.ink : C.muted }}>{side.name}</span>
      </div>
    </div>
  );
}

// ── type thumbnail card ──
function TypeThumb({ type, onClick, size = 'md' }) {
  const g = type.colors;
  const h = size === 'lg' ? 148 : 116;
  return (
    <button onClick={() => onClick(type.code)} className="pm-thumb" style={{
      border: 'none', cursor: 'pointer', padding: 0, background: C.panel, borderRadius: 20, overflow: 'hidden',
      boxShadow: '0 3px 14px rgba(168,107,52,0.08)', textAlign: 'left', display: 'flex', flexDirection: 'column',
      transition: 'transform .18s ease, box-shadow .18s ease',
    }}>
      <div style={{ height: h, background: g.soft, overflow: 'hidden' }}>
        <img src={type.img} alt={type.nick} style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
      </div>
      <div style={{ padding: '11px 14px 13px' }}>
        <div style={{ fontFamily: "'Fredoka', sans-serif", fontWeight: 600, fontSize: 12, letterSpacing: '2px', color: g.ink }}>{type.code}</div>
        <div style={{ fontFamily: "'Fredoka', sans-serif", fontWeight: 600, fontSize: 17, color: C.ink, lineHeight: 1.1, marginTop: 2 }}>{type.nick}</div>
        <div style={{ fontFamily: "'Nunito', sans-serif", fontWeight: 700, fontSize: 12.5, color: C.muted, marginTop: 3 }}>{S.theSpecies(type.species)}</div>
      </div>
    </button>
  );
}

Object.assign(window, { PawIcon, Sparkle, Cloud, AppIcon, NavBar, Footer, Btn, TraitBar, TypeThumb, AppStoreBadge, AppQR });
