/* Shared UI components for the Delishpot site */

const { useState, useEffect, useRef } = React;

/* ------------------------ Foundational bits ------------------------ */

function Pill({ children, tone = 'teal', size = 'sm', style = {}, onClick }) {
  const tones = {
    teal:   { bg: 'rgba(14,110,106,0.10)', fg: '#0e6e6a' },
    orange: { bg: 'rgba(232,122,31,0.14)', fg: '#c45f10' },
    cream:  { bg: 'rgba(247,238,219,1)',   fg: '#0e6e6a' },
    outline:{ bg: 'transparent',           fg: 'currentColor', border: '1px solid currentColor' },
    solid:  { bg: '#0e6e6a',               fg: '#f7eedb' },
  };
  const t = tones[tone] || tones.teal;
  return (
    <span onClick={onClick} style={{
      display: 'inline-flex', alignItems: 'center', gap: 6,
      background: t.bg, color: t.fg, border: t.border || 'none',
      padding: size === 'lg' ? '8px 14px' : '4px 10px',
      borderRadius: 999, fontSize: size === 'lg' ? 14 : 11,
      fontWeight: 600, letterSpacing: '0.04em', textTransform: 'uppercase',
      whiteSpace: 'nowrap', cursor: onClick ? 'pointer' : 'default',
      ...style,
    }}>{children}</span>
  );
}

function Btn({ children, variant = 'primary', size = 'md', onClick, style = {}, type = 'button', disabled, fullWidth, icon }) {
  const variants = {
    primary:   { bg: '#0e6e6a', fg: '#f7eedb', border: '1px solid #0e6e6a' },
    orange:    { bg: '#e87a1f', fg: '#fff',    border: '1px solid #e87a1f' },
    ghost:     { bg: 'transparent', fg: '#0e6e6a', border: '1px solid rgba(14,110,106,0.25)' },
    ghostDark: { bg: 'transparent', fg: '#f7eedb', border: '1px solid rgba(247,238,219,0.3)' },
    cream:     { bg: '#f7eedb', fg: '#0e6e6a', border: '1px solid #f7eedb' },
    invert:    { bg: '#fbf5e6', fg: '#073c3a', border: '1px solid #fbf5e6' },
  };
  const v = variants[variant] || variants.primary;
  const pad = size === 'lg' ? '16px 28px' : size === 'sm' ? '8px 14px' : '12px 20px';
  const fs = size === 'lg' ? 15 : size === 'sm' ? 13 : 14;
  return (
    <button type={type} onClick={onClick} disabled={disabled} style={{
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 10,
      background: v.bg, color: v.fg, border: v.border,
      padding: pad, fontSize: fs, fontWeight: 600,
      borderRadius: 999, cursor: disabled ? 'not-allowed' : 'pointer',
      letterSpacing: '0.01em', transition: 'transform .15s ease, background .15s ease',
      fontFamily: '"Plus Jakarta Sans", system-ui',
      opacity: disabled ? 0.5 : 1,
      width: fullWidth ? '100%' : 'auto',
      ...style,
    }}
    onMouseDown={(e)=>e.currentTarget.style.transform='scale(0.98)'}
    onMouseUp={(e)=>e.currentTarget.style.transform='scale(1)'}
    onMouseLeave={(e)=>e.currentTarget.style.transform='scale(1)'}>
      {children}
      {icon && <span aria-hidden="true">{icon}</span>}
    </button>
  );
}

/* ------------------------ Photo fallback ------------------------
   Quiet brand surface for dishes without a matched photo yet. */
function DishPlaceholder({ label, ratio = '4/3', tone = 'light', radius = 18, accent = '#e87a1f' }) {
  const bg = tone === 'dark' ? '#0a4a47' : '#ecdfb9';
  const stripe = tone === 'dark' ? '#0e6e6a' : '#dcc88c';
  return (
    <div aria-label={label} role="img" style={{
      aspectRatio: ratio, width: '100%', borderRadius: radius,
      background: `repeating-linear-gradient(135deg, ${bg} 0 14px, ${stripe} 14px 15px)`,
      position: 'relative', overflow: 'hidden',
      boxShadow: tone === 'dark' ? 'inset 0 0 0 1px rgba(255,255,255,0.04)' : 'inset 0 0 0 1px rgba(14,110,106,0.06)',
    }}>
      <span aria-hidden="true" style={{
        position: 'absolute', right: 14, bottom: 14,
        width: 8, height: 8, borderRadius: '50%', background: accent,
      }}></span>
    </div>
  );
}

function FoodPhoto({ imageId, ratio = '4/3', radius = 18, fit = 'cover', position = 'center', style = {}, fallbackLabel, tone, accent }) {
  const image = FOOD_IMAGES[imageId];
  if (!image) {
    return <DishPlaceholder label={fallbackLabel || 'Delishpot dish'} ratio={ratio} radius={radius} tone={tone} accent={accent} />;
  }

  return (
    <figure data-food-tags={image.tags.join(' ')} style={{
      aspectRatio: ratio, width: '100%', height: ratio === 'auto' ? '100%' : 'auto',
      margin: 0, borderRadius: radius,
      overflow: 'hidden', background: '#ecdfb9',
      ...style,
    }}>
      <img src={image.src} alt={image.alt} loading="lazy" style={{
        display: 'block', width: '100%', height: '100%',
        objectFit: fit, objectPosition: position,
      }} />
    </figure>
  );
}

/* ------------------------ Nav + Footer ------------------------ */

function TopNav({ page, setPage, openCart, cartCount, dark, accent }) {
  const items = [
    { id: 'home', label: 'Home' },
    { id: 'menu', label: 'Menu' },
    { id: 'bulk', label: 'Bulk & Catering' },
    { id: 'about', label: 'Our Story' },
    { id: 'contact', label: 'Contact' },
  ];
  const fg = dark ? '#f7eedb' : '#0e6e6a';
  const bg = dark ? 'rgba(7,60,58,0.85)' : 'rgba(241,230,207,0.85)';
  const border = dark ? 'rgba(247,238,219,0.10)' : 'rgba(14,110,106,0.10)';
  return (
    <header style={{
      position: 'sticky', top: 0, zIndex: 40,
      backdropFilter: 'blur(14px)', WebkitBackdropFilter: 'blur(14px)',
      background: bg, borderBottom: `1px solid ${border}`,
    }}>
      <div className="dp-shell" style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '14px 0', gap: 24 }}>
        <div onClick={()=>setPage('home')} style={{ cursor: 'pointer', display: 'inline-flex' }}>
          <Logo size={0.55} color={fg} dot={accent} tagline={false} />
        </div>
        <nav className="dp-nav-desktop" style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
          {items.map((it) => {
            const active = page === it.id || (it.id === 'menu' && page === 'menu');
            return (
              <button key={it.id} onClick={()=>setPage(it.id)} style={{
                background: active ? (dark ? 'rgba(247,238,219,0.10)' : 'rgba(14,110,106,0.08)') : 'transparent',
                color: fg, border: 'none',
                fontSize: 14, fontWeight: 500, fontFamily: '"Plus Jakarta Sans", system-ui',
                padding: '10px 14px', borderRadius: 999, cursor: 'pointer',
                letterSpacing: '0.005em',
              }}>{it.label}</button>
            );
          })}
        </nav>
        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 10 }}>
          <button onClick={openCart} aria-label="Open cart" style={{
            position: 'relative', display: 'inline-flex', alignItems: 'center', gap: 8,
            background: accent, color: '#fff', border: 'none',
            padding: '10px 18px 10px 14px', borderRadius: 999, cursor: 'pointer',
            fontSize: 13, fontWeight: 700, letterSpacing: '0.02em',
            fontFamily: '"Plus Jakarta Sans", system-ui',
          }}>
            <span style={{ fontSize: 15 }}>🍲</span>
            <span>Cart</span>
            <span style={{
              minWidth: 22, height: 22, padding: '0 6px',
              background: '#fff', color: accent, borderRadius: 999,
              fontSize: 12, fontWeight: 800, display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            }}>{cartCount}</span>
          </button>
        </div>
      </div>
      <MobileNav page={page} setPage={setPage} dark={dark} accent={accent} />
    </header>
  );
}

function MobileNav({ page, setPage, dark, accent }) {
  const items = [
    { id: 'home', label: 'Home' },
    { id: 'menu', label: 'Menu' },
    { id: 'bulk', label: 'Bulk' },
    { id: 'about', label: 'Story' },
    { id: 'contact', label: 'Contact' },
  ];
  return (
    <nav className="dp-nav-mobile" style={{
      display: 'none', overflowX: 'auto', gap: 6, padding: '0 20px 12px',
      borderTop: `1px solid ${dark ? 'rgba(247,238,219,0.08)' : 'rgba(14,110,106,0.08)'}`,
    }}>
      {items.map((it) => {
        const active = page === it.id;
        return (
          <button key={it.id} onClick={()=>setPage(it.id)} style={{
            flex: '0 0 auto',
            background: active ? accent : 'transparent',
            color: active ? '#fff' : (dark ? '#f7eedb' : '#0e6e6a'),
            border: `1px solid ${active ? accent : (dark ? 'rgba(247,238,219,0.18)' : 'rgba(14,110,106,0.18)')}`,
            padding: '8px 14px', borderRadius: 999, cursor: 'pointer',
            fontSize: 13, fontWeight: 600, marginTop: 6,
            fontFamily: '"Plus Jakarta Sans", system-ui',
          }}>{it.label}</button>
        );
      })}
    </nav>
  );
}

function Footer({ dark, accent, setPage }) {
  const fg = dark ? '#f7eedb' : '#0e6e6a';
  const mute = dark ? 'rgba(247,238,219,0.6)' : '#6b6253';
  const border = dark ? 'rgba(247,238,219,0.10)' : 'rgba(14,110,106,0.14)';
  return (
    <footer style={{ borderTop: `1px solid ${border}`, marginTop: 80, padding: '60px 0 28px' }}>
      <div className="dp-shell">
        <div className="dp-footer-grid" style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr 1fr 1fr', gap: 40 }}>
          <div>
            <Logo size={0.7} color={fg} dot={accent} />
            <p style={{ marginTop: 18, color: mute, fontSize: 14, lineHeight: 1.65, maxWidth: 340 }}>
              Home-style Nigerian cooking, delivered hot across Lagos. Bulk orders, weekly meal plans, and catering for the people you love most.
            </p>
          </div>
          <div>
            <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.14em', textTransform: 'uppercase', color: mute, marginBottom: 14 }}>Order</div>
            <FooterLink onClick={()=>setPage('menu')} fg={fg}>Daily Menu</FooterLink>
            <FooterLink onClick={()=>setPage('bulk')} fg={fg}>Bulk & Catering</FooterLink>
            <FooterLink onClick={()=>setPage('menu')} fg={fg}>Weekly Meal Plan</FooterLink>
          </div>
          <div>
            <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.14em', textTransform: 'uppercase', color: mute, marginBottom: 14 }}>Company</div>
            <FooterLink onClick={()=>setPage('about')} fg={fg}>Our Story</FooterLink>
            <FooterLink onClick={()=>setPage('contact')} fg={fg}>Contact</FooterLink>
            <FooterLink fg={fg}>Careers</FooterLink>
          </div>
          <div>
            <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.14em', textTransform: 'uppercase', color: mute, marginBottom: 14 }}>Reach us</div>
            <div style={{ color: fg, fontSize: 15, fontWeight: 600 }}>0704 200 4295</div>
            <div style={{ color: mute, fontSize: 13, margin: '4px 0 14px' }}>Call for orders and bulk quotes</div>
            <div style={{ display: 'flex', gap: 10 }}>
              <SocialChip dark={dark} accent={accent}>IG</SocialChip>
              <SocialChip dark={dark} accent={accent}>WA</SocialChip>
              <SocialChip dark={dark} accent={accent}>X</SocialChip>
            </div>
          </div>
        </div>
        <div style={{
          marginTop: 50, paddingTop: 22,
          borderTop: `1px solid ${border}`,
          display: 'flex', justifyContent: 'space-between', flexWrap: 'wrap', gap: 12,
          color: mute, fontSize: 12, letterSpacing: '0.02em',
        }}>
          <span>© 2026 Delishpot Kitchens · Lagos, Nigeria</span>
          <span style={{ fontFamily: '"Fraunces", serif', fontStyle: 'italic' }}>…for the love of food</span>
        </div>
      </div>
    </footer>
  );
}

function FooterLink({ children, onClick, fg }) {
  return (
    <div onClick={onClick} style={{
      color: fg, fontSize: 14, fontWeight: 500, padding: '6px 0',
      cursor: onClick ? 'pointer' : 'default',
    }}>{children}</div>
  );
}

function SocialChip({ children, dark, accent }) {
  return (
    <div style={{
      width: 36, height: 36, borderRadius: '50%',
      background: dark ? 'rgba(247,238,219,0.08)' : 'rgba(14,110,106,0.08)',
      color: dark ? '#f7eedb' : '#0e6e6a',
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      fontSize: 11, fontWeight: 800, letterSpacing: '0.05em', cursor: 'pointer',
      border: `1px solid ${dark ? 'rgba(247,238,219,0.10)' : 'rgba(14,110,106,0.10)'}`,
    }}>{children}</div>
  );
}

/* ------------------------ Section header (editorial / bold) ------------------------ */

function SectionHeader({ kicker, title, sub, align = 'left', dark, accent, italicWord }) {
  const fg = dark ? '#f7eedb' : '#0e6e6a';
  const mute = dark ? 'rgba(247,238,219,0.7)' : '#6b6253';
  return (
    <div style={{ textAlign: align, maxWidth: align === 'center' ? 720 : 'none', margin: align === 'center' ? '0 auto' : 0 }}>
      {kicker && (
        <div style={{
          display: 'inline-flex', alignItems: 'center', gap: 10, marginBottom: 18,
          fontSize: 11, fontWeight: 700, letterSpacing: '0.18em', textTransform: 'uppercase',
          color: accent,
        }}>
          <span style={{ width: 22, height: 1, background: accent, display: 'inline-block' }}></span>
          {kicker}
        </div>
      )}
      <h2 style={{
        fontFamily: '"Bricolage Grotesque", system-ui', fontWeight: 700,
        fontSize: 'clamp(34px, 5vw, 60px)', lineHeight: 1.02, letterSpacing: '-0.025em',
        color: fg, margin: 0, textWrap: 'balance',
      }}>
        {italicWord ? title.split(italicWord).map((part, i, arr) => (
          <React.Fragment key={i}>
            {part}
            {i < arr.length - 1 && (
              <span style={{ fontFamily: '"Fraunces", serif', fontStyle: 'italic', fontWeight: 400, color: accent }}>{italicWord}</span>
            )}
          </React.Fragment>
        )) : title}
      </h2>
      {sub && (
        <p style={{
          color: mute, fontSize: 17, lineHeight: 1.55, marginTop: 18,
          maxWidth: 580, textWrap: 'pretty',
          marginLeft: align === 'center' ? 'auto' : 0,
          marginRight: align === 'center' ? 'auto' : 0,
        }}>{sub}</p>
      )}
    </div>
  );
}

/* ------------------------ Dish cards ------------------------ */

function DishCard({ item, cardStyle, dark, accent, onAdd }) {
  // cardStyle: 'photo' | 'editorial'
  const fg = dark ? '#f7eedb' : '#0e6e6a';
  const sub = dark ? 'rgba(247,238,219,0.65)' : '#6b6253';
  const surface = dark ? '#0a4a47' : '#fbf5e6';
  const border = dark ? 'rgba(247,238,219,0.08)' : 'rgba(14,110,106,0.10)';

  if (cardStyle === 'editorial') {
    return (
      <div className="dp-dish-card-editorial" style={{
        padding: '20px 0',
        borderBottom: `1px solid ${border}`,
        display: 'grid', gridTemplateColumns: '1fr auto auto', gap: 18, alignItems: 'center',
      }}>
        <div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 4 }}>
            <h3 style={{ fontFamily: '"Bricolage Grotesque", system-ui', fontWeight: 600, fontSize: 22, color: fg, margin: 0, letterSpacing: '-0.01em' }}>{item.name}</h3>
            {item.tag && <Pill tone="orange" size="sm">{item.tag}</Pill>}
          </div>
          {item.desc && <p style={{ color: sub, fontSize: 13.5, margin: 0, lineHeight: 1.5 }}>{item.desc}</p>}
        </div>
        <div style={{
          fontFamily: '"Bricolage Grotesque", system-ui', fontWeight: 600,
          fontSize: 20, color: fg, letterSpacing: '-0.01em',
        }}>{ngn(item.price)}</div>
        <button onClick={()=>onAdd(item)} aria-label={`Add ${item.name} to cart`} style={{
          width: 40, height: 40, borderRadius: '50%',
          background: accent, color: '#fff', border: 'none',
          fontSize: 20, fontWeight: 600, cursor: 'pointer',
          lineHeight: 1, display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        }}>+</button>
      </div>
    );
  }

  // photo card
  return (
    <div style={{
      background: surface, border: `1px solid ${border}`,
      borderRadius: 22, padding: 14, display: 'flex', flexDirection: 'column', gap: 14,
      transition: 'transform .2s ease, box-shadow .2s ease',
    }}
    onMouseEnter={(e)=>{ e.currentTarget.style.transform='translateY(-2px)'; e.currentTarget.style.boxShadow = dark ? '0 14px 30px rgba(0,0,0,0.25)' : '0 14px 30px rgba(14,110,106,0.10)'; }}
    onMouseLeave={(e)=>{ e.currentTarget.style.transform='translateY(0)'; e.currentTarget.style.boxShadow = 'none'; }}>
      <FoodPhoto imageId={item.imageId} fallbackLabel={item.name} tone={dark ? 'dark' : 'light'} accent={accent} radius={14} />
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 12 }}>
        <div style={{ minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
            <h3 style={{ fontFamily: '"Bricolage Grotesque", system-ui', fontWeight: 600, fontSize: 18, color: fg, margin: 0, letterSpacing: '-0.01em' }}>{item.name}</h3>
          </div>
          {item.tag && <Pill tone="orange" size="sm">{item.tag}</Pill>}
          {item.desc && <p style={{ color: sub, fontSize: 12.5, margin: '8px 0 0', lineHeight: 1.5 }}>{item.desc}</p>}
        </div>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 'auto', paddingTop: 4 }}>
        <span style={{ fontFamily: '"Bricolage Grotesque", system-ui', fontWeight: 700, fontSize: 18, color: fg }}>{ngn(item.price)}</span>
        <Btn size="sm" variant={dark ? 'cream' : 'primary'} onClick={()=>onAdd(item)}>Add to pot</Btn>
      </div>
    </div>
  );
}

Object.assign(window, {
  Pill, Btn, DishPlaceholder, FoodPhoto,
  TopNav, Footer, SectionHeader, DishCard,
});
