// Shared UI primitives
const { useState, useEffect, useRef, useMemo } = React;

function Logo({ size = 44, invert = false }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
      <img
        src="assets/logo.png"
        alt="Los Nobles"
        style={{
          height: size,
          width: 'auto',
          filter: invert ? 'invert(1) brightness(1.1)' : 'none',
        }}
      />
    </div>
  );
}

function Button({ children, variant = 'primary', size = 'md', onClick, type = 'button', disabled, style, full }) {
  const base = {
    display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
    borderRadius: 999, fontWeight: 600, letterSpacing: '-0.005em',
    transition: 'transform .12s ease, background .15s ease, box-shadow .15s ease, color .15s ease',
    cursor: disabled ? 'not-allowed' : 'pointer',
    opacity: disabled ? 0.5 : 1,
    width: full ? '100%' : 'auto',
    border: '1px solid transparent',
    whiteSpace: 'nowrap',
  };
  const sizes = {
    sm: { padding: '8px 14px', fontSize: 13 },
    md: { padding: '12px 22px', fontSize: 14 },
    lg: { padding: '16px 28px', fontSize: 15 },
  };
  const variants = {
    primary: { background: 'var(--accent)', color: '#fff' },
    secondary: { background: 'var(--ink)', color: 'var(--paper)' },
    ghost: { background: 'transparent', color: 'var(--ink)', border: '1px solid var(--line)' },
    outline: { background: 'transparent', color: 'var(--accent)', border: '1.5px solid var(--accent)' },
    link: { background: 'transparent', color: 'var(--accent)', padding: 0 },
  };
  return (
    <button
      type={type}
      onClick={onClick}
      disabled={disabled}
      style={{ ...base, ...sizes[size], ...variants[variant], ...style }}
      onMouseDown={e => !disabled && (e.currentTarget.style.transform = 'translateY(1px)')}
      onMouseUp={e => (e.currentTarget.style.transform = 'translateY(0)')}
      onMouseLeave={e => (e.currentTarget.style.transform = 'translateY(0)')}
    >
      {children}
    </button>
  );
}

function Tag({ children, tone = 'neutral' }) {
  const tones = {
    neutral: { background: 'var(--paper-warm)', color: 'var(--ink-soft)' },
    accent: { background: 'color-mix(in oklab, var(--accent) 14%, transparent)', color: 'var(--accent-deep)' },
    ok: { background: 'color-mix(in oklab, var(--ok) 14%, transparent)', color: 'var(--ok)' },
  };
  return (
    <span
      className="mono"
      style={{
        display: 'inline-flex', alignItems: 'center', gap: 4,
        fontSize: 10.5, fontWeight: 500, padding: '4px 8px',
        borderRadius: 4, textTransform: 'uppercase', letterSpacing: '0.08em',
        ...tones[tone],
      }}
    >
      {children}
    </span>
  );
}

// Simple placeholder for dishes without a photo — striped parchment
function DishPlaceholder({ label = 'dish photo', ratio = '4/3' }) {
  return (
    <div style={{
      aspectRatio: ratio,
      background: 'repeating-linear-gradient(135deg, var(--paper-warm) 0 10px, color-mix(in oklab, var(--paper-warm) 70%, var(--line)) 10px 11px)',
      color: 'var(--muted)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      fontFamily: 'JetBrains Mono, monospace', fontSize: 11,
      letterSpacing: '0.1em', textTransform: 'uppercase',
      border: '1px solid var(--line)',
      borderRadius: 8,
    }}>
      {label}
    </div>
  );
}

function Field({ label, hint, error, children, style }) {
  return (
    <label style={{ display: 'flex', flexDirection: 'column', gap: 6, ...style }}>
      <span style={{ fontSize: 12, fontWeight: 600, letterSpacing: '0.04em', textTransform: 'uppercase', color: 'var(--ink-soft)' }}>
        {label}
      </span>
      {children}
      {hint && !error && <span style={{ fontSize: 12, color: 'var(--muted)' }}>{hint}</span>}
      {error && <span style={{ fontSize: 12, color: 'var(--err)' }}>{error}</span>}
    </label>
  );
}

const inputStyle = {
  padding: '12px 14px',
  borderRadius: 10,
  border: '1px solid var(--line)',
  background: 'var(--card)',
  color: 'var(--ink)',
  fontSize: 15,
  outline: 'none',
  transition: 'border-color .15s ease, box-shadow .15s ease',
};

function TextInput(props) {
  return (
    <input
      {...props}
      style={{ ...inputStyle, ...(props.style || {}) }}
      onFocus={e => {
        e.target.style.borderColor = 'var(--accent)';
        e.target.style.boxShadow = '0 0 0 3px color-mix(in oklab, var(--accent) 18%, transparent)';
      }}
      onBlur={e => {
        e.target.style.borderColor = 'var(--line)';
        e.target.style.boxShadow = 'none';
      }}
    />
  );
}

// Modal shell
function Modal({ open, onClose, children, width = 960, title }) {
  useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') onClose?.(); };
    document.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => {
      document.removeEventListener('keydown', onKey);
      document.body.style.overflow = '';
    };
  }, [open, onClose]);
  if (!open) return null;
  return (
    <div
      onClick={onClose}
      className="ln-modal-backdrop"
      style={{
        position: 'fixed', inset: 0, zIndex: 90,
        background: 'rgba(20,14,8,.55)',
        backdropFilter: 'blur(4px)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: 20,
        animation: 'fadeIn .2s ease',
      }}
    >
      <div
        onClick={e => e.stopPropagation()}
        className="ln-modal-card"
        style={{
          background: 'var(--paper)',
          borderRadius: 18,
          width: '100%',
          maxWidth: width,
          maxHeight: '92vh',
          overflow: 'hidden',
          display: 'flex',
          flexDirection: 'column',
          boxShadow: 'var(--shadow-lg)',
          animation: 'popIn .24s cubic-bezier(.2,.8,.3,1.2)',
        }}
      >
        {title && (
          <div className="ln-modal-head" style={{
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            padding: '18px 24px', borderBottom: '1px solid var(--line)',
          }}>
            <div className="serif" style={{ fontSize: 22, fontWeight: 600 }}>{title}</div>
            <button
              onClick={onClose}
              aria-label="Close"
              style={{
                width: 36, height: 36, borderRadius: 999,
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                color: 'var(--ink-soft)',
                transition: 'background .15s ease',
                flexShrink: 0,
              }}
              onMouseEnter={e => e.currentTarget.style.background = 'var(--paper-warm)'}
              onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
            >
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M18 6L6 18M6 6l12 12"/></svg>
            </button>
          </div>
        )}
        <div style={{ overflow: 'auto', flex: 1 }}>
          {children}
        </div>
      </div>
    </div>
  );
}

// Icons
const Icon = {
  bag: (p) => (<svg width={p?.size||20} height={p?.size||20} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M6 7h12l-1.2 12.1a2 2 0 0 1-2 1.9H9.2a2 2 0 0 1-2-1.9L6 7z"/><path d="M9 7V5a3 3 0 0 1 6 0v2"/></svg>),
  calendar: (p) => (<svg width={p?.size||20} height={p?.size||20} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="5" width="18" height="16" rx="2"/><path d="M3 10h18M8 3v4M16 3v4"/></svg>),
  moped: (p) => (<svg width={p?.size||20} height={p?.size||20} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><circle cx="6" cy="17" r="3"/><circle cx="18" cy="17" r="3"/><path d="M9 17h6m-6-7h4l5 7"/><path d="M13 5h3l1 3"/></svg>),
  plus: (p) => (<svg width={p?.size||16} height={p?.size||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"><path d="M12 5v14M5 12h14"/></svg>),
  minus: (p) => (<svg width={p?.size||16} height={p?.size||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"><path d="M5 12h14"/></svg>),
  arrow: (p) => (<svg width={p?.size||16} height={p?.size||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14M13 6l6 6-6 6"/></svg>),
  check: (p) => (<svg width={p?.size||18} height={p?.size||18} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12l5 5L20 7"/></svg>),
  pin: (p) => (<svg width={p?.size||18} height={p?.size||18} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M12 22s7-7.5 7-13a7 7 0 1 0-14 0c0 5.5 7 13 7 13z"/><circle cx="12" cy="9" r="2.5"/></svg>),
  clock: (p) => (<svg width={p?.size||18} height={p?.size||18} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></svg>),
  phone: (p) => (<svg width={p?.size||18} height={p?.size||18} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M5 4h3l2 5-2 1a12 12 0 0 0 6 6l1-2 5 2v3a2 2 0 0 1-2 2A17 17 0 0 1 3 6a2 2 0 0 1 2-2z"/></svg>),
  external: (p) => (<svg width={p?.size||14} height={p?.size||14} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M14 4h6v6M10 14L20 4M20 14v5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1h5"/></svg>),
};

// Global keyframes + responsive helpers
const _globalStyle = document.createElement('style');
_globalStyle.textContent = `
@keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
@keyframes popIn { from { opacity: 0; transform: translateY(8px) scale(.98) } to { opacity: 1; transform: translateY(0) scale(1) } }
@keyframes slideInRight { from { transform: translateX(12px); opacity: 0 } to { transform: translateX(0); opacity: 1 } }
@keyframes cartPulse { 0%{transform:scale(1)} 30%{transform:scale(1.15)} 100%{transform:scale(1)} }

/* Modal — go near full-screen on phones */
@media (max-width: 720px) {
  .ln-modal-backdrop { padding: 0 !important; align-items: stretch !important; }
  .ln-modal-card {
    max-width: 100% !important;
    max-height: 100vh !important;
    height: 100vh;
    border-radius: 0 !important;
  }
  .ln-modal-head { padding: 14px 18px !important; }
  .ln-modal-head .serif { font-size: 18px !important; }
}

/* Form grids inside modals — collapse to single column on small screens */
.ln-form-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; }
@media (max-width: 640px) {
  .ln-form-grid { grid-template-columns: 1fr; }
}

/* Standard modal section padding — auto-adapts on mobile */
.ln-modal-section { padding: 28px 32px 32px; }
.ln-modal-section-tight { padding: 44px 36px 36px; }
.ln-modal-section-confirm { padding: 56px 32px 48px; }
@media (max-width: 540px) {
  .ln-modal-section { padding: 22px 18px 24px !important; }
  .ln-modal-section-tight { padding: 32px 20px 24px !important; }
  .ln-modal-section-confirm { padding: 40px 20px 32px !important; }
}
`;
document.head.appendChild(_globalStyle);

// Fallback modal shown when a service is in 'phone' or 'closed' mode
function ServiceFallbackModal({ open, onClose, service }) {
  const { t } = useT();
  const fb = t.fallback;
  const store = useLnStore();
  const mode = store.serviceModes[service];
  if (mode === 'online') return null;
  const iconBg = mode === 'closed' ? 'color-mix(in oklab, var(--muted) 22%, transparent)' : 'color-mix(in oklab, var(--accent) 14%, transparent)';
  const iconColor = mode === 'closed' ? 'var(--ink-soft)' : 'var(--accent)';
  let title, body;
  if (mode === 'phone') {
    title = service === 'reservation' ? fb.phoneTitleReserve : fb.phoneTitle;
    body = service === 'reservation' ? fb.phoneBodyReserve : (service === 'delivery' ? fb.phoneBodyDelivery : fb.phoneBody);
  } else {
    title = fb.closedTitle;
    body = service === 'reservation' ? fb.closedBodyReserve : (service === 'delivery' ? fb.closedBodyDelivery : fb.closedBodyTakeaway);
  }
  return (
    <Modal open={open} onClose={onClose} width={500}>
      <div className="ln-modal-section-tight" style={{ textAlign: 'center' }}>
        <div style={{ width: 64, height: 64, borderRadius: 20, background: iconBg, color: iconColor, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', marginBottom: 18 }}>
          {mode === 'closed' ? <Icon.clock size={30}/> : <Icon.phone size={30} />}
        </div>
        <h2 className="serif" style={{ margin: '0 0 10px', fontSize: 26, fontWeight: 600, letterSpacing: '-0.02em' }}>{title}</h2>
        <p style={{ margin: '0 auto 22px', color: 'var(--ink-soft)', fontSize: 15, lineHeight: 1.6, maxWidth: 380 }}>{body}</p>
        {mode === 'phone' && (
          <>
            <div style={{ background: 'var(--paper-warm)', borderRadius: 14, padding: '18px 20px', margin: '0 auto 18px', maxWidth: 360 }}>
              <div className="mono" style={{ fontSize: 11, letterSpacing: '0.15em', textTransform: 'uppercase', color: 'var(--muted)', marginBottom: 6 }}>Los Nobles Tacos</div>
              <a href={`tel:${store.settings.phone.replace(/\s/g,'')}`} className="serif" style={{ display: 'block', fontSize: 30, fontWeight: 600, color: 'var(--accent)', textDecoration: 'none', letterSpacing: '-0.015em' }}>{store.settings.phone}</a>
              <div style={{ fontSize: 13, color: 'var(--ink-soft)', marginTop: 8 }}>{store.settings.phoneHours}</div>
            </div>
            <div style={{ display: 'flex', gap: 10, justifyContent: 'center', flexWrap: 'wrap' }}>
              <Button variant="ghost" onClick={onClose}>{fb.backToSite}</Button>
              <Button variant="primary" size="lg" onClick={() => { window.location.href = `tel:${store.settings.phone.replace(/\s/g,'')}`; }}>
                <Icon.phone size={16}/> {fb.callNow}
              </Button>
            </div>
          </>
        )}
        {mode === 'closed' && (
          <div style={{ display: 'flex', justifyContent: 'center' }}>
            <Button variant="primary" onClick={onClose}>{fb.backToSite}</Button>
          </div>
        )}
      </div>
    </Modal>
  );
}

Object.assign(window, { Logo, Button, Tag, DishPlaceholder, Field, TextInput, Modal, Icon, inputStyle, ServiceFallbackModal });
