// TLB primitives — editorial, monochrome, strict.
// Reads from window.TLB_TOKENS. Reads tweak state from window.TLB_TWEAKS.

const C = window.TLB_TOKENS.color;
const F = window.TLB_TOKENS.font;

// ── Type helpers ────────────────────────────────────────────────
const tweak = () => window.TLB_TWEAKS || {};
const displayFamily = () => {
  const f = tweak().displayFont;
  if (f === 'cormorant') return "'Cormorant Garamond', Georgia, serif";
  return F.display;
};
const uiFamily = () => {
  const f = tweak().uiFont;
  if (f === 'inter') return "Inter, system-ui, sans-serif";
  return F.ui;
};
const density = () => (tweak().density || 'comfortable');
const ctaRadius = () => (tweak().ctaShape === 'square' ? 0 : 100);
const heroRatio = () => (tweak().heroRatio || '4/5');

function Display({ children, size = 32, weight = 500, italic = false, color = C.ink, ls = -0.01, lh = 1.1, style = {}, as: Tag = 'div' }) {
  return (
    <Tag style={{
      fontFamily: displayFamily(),
      fontSize: size, fontWeight: weight, color,
      fontStyle: italic ? 'italic' : 'normal',
      letterSpacing: `${ls}em`, lineHeight: lh,
      ...style,
    }}>{children}</Tag>
  );
}

function Sans({ children, size = 14, weight = 400, color = C.ink, ls = 0, lh = 1.5, upper = false, style = {}, as: Tag = 'div' }) {
  return (
    <Tag style={{
      fontFamily: uiFamily(),
      fontSize: size, fontWeight: weight, color,
      letterSpacing: `${ls}em`, lineHeight: lh,
      textTransform: upper ? 'uppercase' : 'none',
      ...style,
    }}>{children}</Tag>
  );
}

function Eyebrow({ children, color = C.mid, style = {} }) {
  return <Sans size={10} weight={600} color={color} ls={0.12} upper style={style}>{children}</Sans>;
}

// ── Buttons ─────────────────────────────────────────────────────
function Button({ children, variant = 'primary', size = 'md', full = false, onClick, style = {}, leading, trailing, disabled }) {
  const radius = ctaRadius();
  const h = size === 'lg' ? 52 : size === 'sm' ? 36 : 46;
  const pad = size === 'lg' ? '0 32px' : size === 'sm' ? '0 16px' : '0 24px';
  const fs = size === 'lg' ? 13 : size === 'sm' ? 11 : 12;

  const base = {
    height: h, padding: pad, borderRadius: radius,
    display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
    fontFamily: uiFamily(), fontSize: fs, fontWeight: 600,
    letterSpacing: '0.12em', textTransform: 'uppercase',
    border: 'none', cursor: disabled ? 'not-allowed' : 'pointer',
    transition: 'all .2s ease',
    width: full ? '100%' : undefined,
    opacity: disabled ? 0.4 : 1,
    ...style,
  };
  const variants = {
    primary:   { background: C.ink, color: C.white },
    secondary: { background: C.white, color: C.ink, border: `1px solid ${C.ink}` },
    ghost:     { background: 'transparent', color: C.ink, textDecoration: 'underline', textUnderlineOffset: 4, letterSpacing: '0.04em', textTransform: 'none', fontWeight: 500, padding: 0 },
    onDark:    { background: C.white, color: C.ink },
    destructive: { background: 'transparent', color: '#9a1c1c', textTransform: 'none', letterSpacing: '0.02em', fontWeight: 500 },
  };
  return (
    <button onClick={onClick} disabled={disabled} style={{ ...base, ...variants[variant] }}>
      {leading}{children}{trailing}
    </button>
  );
}

function IconButton({ name, onClick, size = 38, dark = false, bg, style = {} }) {
  const resolvedBg = bg || (dark ? 'rgba(255,255,255,0.12)' : 'rgba(255,255,255,0.88)');
  return (
    <button onClick={onClick} style={{
      width: size, height: size, borderRadius: '50%',
      background: resolvedBg, border: 'none', cursor: 'pointer',
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      backdropFilter: 'blur(12px)', WebkitBackdropFilter: 'blur(12px)',
      ...style,
    }}>
      <Icon name={name} size={18} color={dark ? C.white : C.ink} />
    </button>
  );
}

// ── Inputs ──────────────────────────────────────────────────────
function Field({ label, value, onChange, placeholder, type = 'text', dark = false, right }) {
  const [focused, setF] = React.useState(false);
  return (
    <label style={{ display: 'block', position: 'relative', marginBottom: 16 }}>
      <div style={{
        position: 'absolute', left: 16,
        top: focused || value ? 8 : 22,
        fontFamily: uiFamily(),
        fontSize: focused || value ? 10 : 14,
        fontWeight: focused || value ? 600 : 400,
        letterSpacing: focused || value ? '0.12em' : 0,
        textTransform: focused || value ? 'uppercase' : 'none',
        color: focused ? C.ink : C.mid,
        transition: 'all .18s ease', pointerEvents: 'none',
      }}>{label}</div>
      <input
        type={type} value={value || ''} onChange={e => onChange && onChange(e.target.value)}
        placeholder={focused ? placeholder : ''}
        onFocus={() => setF(true)} onBlur={() => setF(false)}
        style={{
          width: '100%', height: 60, boxSizing: 'border-box',
          padding: '22px 16px 6px',
          border: `1px solid ${focused ? C.ink : C.border}`,
          borderRadius: 12, background: dark ? C.near : C.white,
          fontFamily: uiFamily(), fontSize: 15, color: C.ink,
          outline: 'none', transition: 'border .15s',
        }}
      />
      {right && <div style={{ position: 'absolute', right: 14, top: 19 }}>{right}</div>}
    </label>
  );
}

function Toggle({ on, onChange }) {
  return (
    <button onClick={() => onChange(!on)} style={{
      width: 44, height: 26, borderRadius: 100,
      background: on ? C.ink : C.border, border: 'none',
      position: 'relative', cursor: 'pointer', transition: 'background .2s',
      padding: 0, flexShrink: 0,
    }}>
      <div style={{
        position: 'absolute', top: 3, left: on ? 21 : 3,
        width: 20, height: 20, borderRadius: '50%',
        background: C.white, transition: 'left .2s',
        boxShadow: '0 1px 3px rgba(0,0,0,0.2)',
      }} />
    </button>
  );
}

function Checkbox({ on, onChange, label }) {
  return (
    <label style={{ display: 'inline-flex', alignItems: 'center', gap: 10, cursor: 'pointer' }}>
      <div onClick={() => onChange(!on)} style={{
        width: 18, height: 18, borderRadius: 3,
        border: `1.5px solid ${on ? C.ink : C.muted}`,
        background: on ? C.ink : 'transparent',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        transition: 'all .15s',
      }}>
        {on && <Icon name="check" size={12} color={C.white} stroke={2.5} />}
      </div>
      {label && <Sans size={14}>{label}</Sans>}
    </label>
  );
}

function Chip({ children, active, onClick, leading }) {
  return (
    <button onClick={onClick} style={{
      height: 36, padding: '0 14px', borderRadius: 100,
      background: active ? C.ink : C.white,
      color: active ? C.white : C.ink,
      border: `1px solid ${active ? C.ink : C.border}`,
      fontFamily: uiFamily(), fontSize: 13, fontWeight: 500,
      display: 'inline-flex', alignItems: 'center', gap: 6,
      cursor: 'pointer', whiteSpace: 'nowrap',
    }}>
      {leading}{children}
    </button>
  );
}

// ── Cards ───────────────────────────────────────────────────────
function VillaCard({ img, name, place, price, nights, sleeps, wide, bookmark, onBookmark, onClick }) {
  return (
    <div onClick={onClick} style={{ cursor: 'pointer', width: '100%' }}>
      <div style={{
        position: 'relative',
        aspectRatio: wide ? '16/10' : '4/5',
        background: `url("${img}") center/cover no-repeat ${C.soft}`,
      }}>
        <div style={{ position: 'absolute', top: 12, right: 12 }}>
          <button onClick={(e) => { e.stopPropagation(); onBookmark && onBookmark(); }} style={{
            width: 36, height: 36, borderRadius: '50%', border: 'none',
            background: 'rgba(255,255,255,0.88)', backdropFilter: 'blur(10px)',
            display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer',
          }}>
            <Icon name="bookmark" size={16} color={C.ink} stroke={bookmark ? 2 : 1.5} style={bookmark ? { fill: C.ink } : {}} />
          </button>
        </div>
      </div>
      <div style={{ paddingTop: 12 }}>
        {place && <Eyebrow>{place}</Eyebrow>}
        <Display size={18} weight={500} style={{ marginTop: 6 }}>{name}</Display>
        {(price || sleeps) && (
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginTop: 8 }}>
            {price && <Sans size={13} color={C.deep}><span style={{ fontFamily: displayFamily(), fontSize: 18, fontWeight: 500 }}>${price}</span> <span style={{ color: C.mid, fontSize: 11 }}>/ night</span></Sans>}
            {sleeps && <Sans size={12} color={C.mid}>Sleeps {sleeps}</Sans>}
          </div>
        )}
      </div>
    </div>
  );
}

function Hairline({ color = C.border, style = {} }) {
  return <div style={{ height: 1, background: color, ...style }} />;
}

// ── Bottom tab bar ──────────────────────────────────────────────
function TabBar({ active = 'explore', onTab }) {
  const tabs = [
    { key: 'explore', icon: 'explore', label: 'Explore' },
    { key: 'search',  icon: 'search',  label: 'Search'  },
    { key: 'saved',   icon: 'bookmark',label: 'Saved'   },
    { key: 'trips',   icon: 'trips',   label: 'Trips'   },
    { key: 'profile', icon: 'profile', label: 'Profile' },
  ];
  return (
    <div style={{
      display: 'flex', background: C.white, borderTop: `1px solid ${C.border}`,
      padding: '8px 0 6px',
    }}>
      {tabs.map(t => {
        const on = active === t.key;
        return (
          <button key={t.key} onClick={() => onTab && onTab(t.key)} style={{
            flex: 1, background: 'none', border: 'none', cursor: 'pointer',
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
            padding: '6px 0',
          }}>
            <Icon name={t.icon} size={22} color={on ? C.ink : C.muted} stroke={on ? 1.8 : 1.5} />
            <span style={{
              fontFamily: uiFamily(), fontSize: 10, fontWeight: on ? 600 : 400,
              letterSpacing: '0.06em', textTransform: 'uppercase',
              color: on ? C.ink : C.muted,
            }}>{t.label}</span>
          </button>
        );
      })}
    </div>
  );
}

// ── Bottom sheet shell ──────────────────────────────────────────
function BottomSheet({ children, style = {} }) {
  return (
    <div style={{
      background: C.white, borderRadius: '24px 24px 0 0',
      boxShadow: '0 -4px 30px rgba(0,0,0,0.08)',
      padding: '12px 0 0',
      ...style,
    }}>
      <div style={{ width: 40, height: 4, background: C.border, borderRadius: 2, margin: '0 auto 12px' }} />
      {children}
    </div>
  );
}

// ── Progress bar ────────────────────────────────────────────────
function Progress({ value = 0 }) {
  return (
    <div style={{ height: 2, background: C.border, position: 'relative' }}>
      <div style={{ height: 2, background: C.ink, width: `${value}%`, transition: 'width .3s' }} />
    </div>
  );
}

// ── Skeleton ────────────────────────────────────────────────────
function Skel({ w = '100%', h = 12, r = 2, style = {} }) {
  return <div style={{ width: w, height: h, borderRadius: r, background: `linear-gradient(90deg, ${C.chip}, ${C.offWhite}, ${C.chip})`, backgroundSize: '200% 100%', animation: 'tlbShimmer 1.6s infinite linear', ...style }} />;
}

// ── Pull-quote ──────────────────────────────────────────────────
function PullQuote({ children, attribution }) {
  return (
    <blockquote style={{ margin: '32px 0', padding: '0 24px', borderLeft: `1px solid ${C.soft}` }}>
      <Display size={22} italic weight={400} lh={1.4} color={C.deep}>"{children}"</Display>
      {attribution && <Sans size={11} weight={600} ls={0.12} upper color={C.mid} style={{ marginTop: 12 }}>— {attribution}</Sans>}
    </blockquote>
  );
}

// ── Modal (desktop) ─────────────────────────────────────────────
function Modal({ children, onClose, width = 560 }) {
  React.useEffect(() => {
    const h = (e) => e.key === 'Escape' && onClose && onClose();
    window.addEventListener('keydown', h);
    return () => window.removeEventListener('keydown', h);
  }, [onClose]);
  return (
    <div style={{ position: 'fixed', inset: 0, zIndex: 100, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'rgba(20,20,20,0.55)', backdropFilter: 'blur(6px)', animation: 'tlbModalIn 0.2s ease' }} onClick={onClose}>
      <div onClick={e => e.stopPropagation()} style={{ width, maxWidth: '92vw', maxHeight: '90vh', background: C.white, boxShadow: '0 40px 80px rgba(0,0,0,0.35)', overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
        {children}
      </div>
      <style>{`@keyframes tlbModalIn { from { opacity: 0; } to { opacity: 1; } }`}</style>
    </div>
  );
}

// ── Expose ──────────────────────────────────────────────────────
Object.assign(window, {
  C_TLB: C, F_TLB: F,
  Display, Sans, Eyebrow,
  Button, IconButton, Modal,
  Field, Toggle, Checkbox, Chip,
  VillaCard, Hairline, PullQuote,
  TabBar, BottomSheet, Progress, Skel,
  displayFamily, uiFamily, density, ctaRadius, heroRatio,
});
