// Shared components: Nav, Footer, Ornament, BranchPicker modal, TrustStrip, MobileBar.

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

const fmt = (n) => (n == null ? '—' : Number(n).toString());

// ─────────────────────────────────────────────────────────────
// Ornament — hairline with diamond
// ─────────────────────────────────────────────────────────────
function Ornament({ label, dark }) {
  const color = dark ? 'rgba(255,255,255,0.35)' : 'var(--rule)';
  return (
    <div className="flex items-center gap-4" style={{color: dark ? 'rgba(255,255,255,0.7)' : 'var(--ink-3)'}}>
      <span style={{flex: 1, height: 1, background: color}} />
      {label && <span className="eyebrow">{label}</span>}
      <span style={{
        width: 8, height: 8, transform: 'rotate(45deg)',
        border: `1px solid ${dark ? 'rgba(255,255,255,0.6)' : 'var(--ink)'}`,
        background: 'transparent',
      }} />
      <span style={{flex: 1, height: 1, background: color}} />
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Wordmark — type-only lockup (not the bitmap logo)
// ─────────────────────────────────────────────────────────────
function Wordmark({ size = 22, light }) {
  return (
    <a href="#/" onClick={(e)=>{e.preventDefault(); window.DDNav.go('home');}}
       className="flex items-center" style={{textDecoration: 'none', gap: 12}}>
      <span style={{
        width: 32, height: 32, display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        border: `1px solid ${light ? '#fff' : 'var(--ink)'}`,
        fontFamily: 'var(--serif)', fontSize: 18, fontStyle: 'italic',
        color: light ? '#fff' : 'var(--ink)',
      }}>D</span>
      <span style={{display: 'flex', flexDirection: 'column', lineHeight: 1}}>
        <span style={{
          fontFamily: 'var(--serif)', fontSize: size, fontWeight: 500, letterSpacing: '-0.005em',
          color: light ? '#fff' : 'var(--ink)',
        }}>Delhi Darbar</span>
        <span style={{
          fontFamily: 'var(--sans)', fontSize: 9, letterSpacing: '0.28em', textTransform: 'uppercase',
          marginTop: 4, color: light ? 'rgba(255,255,255,0.7)' : 'var(--ink-3)',
        }}>Mumbai · Dubai · Since 1973</span>
      </span>
    </a>
  );
}

// ─────────────────────────────────────────────────────────────
// Nav
// ─────────────────────────────────────────────────────────────
function Nav({ route, light, onOrder, lang, setLang }) {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const on = () => setScrolled(window.scrollY > 60);
    window.addEventListener('scroll', on);
    on();
    return () => window.removeEventListener('scroll', on);
  }, []);

  const items = [
    { id: 'menu',     label: 'Menu' },
    { id: 'branches', label: 'Branches' },
    { id: 'catering', label: 'Catering' },
    { id: 'iftar',    label: 'Iftar' },
    { id: 'about',    label: 'About' },
  ];
  const isLight = light && !scrolled;

  return (
    <header className={`nav ${light ? 'is-light' : ''} ${scrolled ? 'is-scrolled' : ''}`}
            style={{
              color: isLight ? '#fff' : 'var(--ink)',
              background: isLight ? 'transparent' : 'rgba(247,241,227,0.92)',
              borderBottom: isLight ? '1px solid rgba(255,255,255,0.18)' : '1px solid var(--rule)',
            }}>
      <div className="container flex items-center justify-between" style={{height: 76}}>
        <Wordmark light={isLight} />
        <nav className="flex items-center gap-8" style={{fontSize: 13}}>
          {items.map(it => (
            <a key={it.id} href={`#/${it.id}`}
               onClick={(e) => { e.preventDefault(); window.DDNav.go(it.id); }}
               className="nav__link"
               style={{
                 color: route === it.id ? (isLight ? '#fff' : 'var(--ink)') : (isLight ? 'rgba(255,255,255,0.88)' : 'var(--ink-2)'),
                 borderBottom: route === it.id ? `1px solid ${isLight ? '#fff' : 'var(--ink)'}` : '1px solid transparent',
                 paddingBottom: 4,
                 fontFamily: 'var(--sans)', fontWeight: 500,
                 letterSpacing: '0.04em',
               }}>
              {it.label}
            </a>
          ))}
        </nav>
        <div className="flex items-center gap-4">
          <button onClick={() => setLang(lang === 'en' ? 'ar' : 'en')}
                  className="eyebrow"
                  style={{
                    color: isLight ? 'rgba(255,255,255,0.88)' : 'var(--ink-2)',
                    background: 'transparent', cursor: 'pointer',
                    padding: '6px 0',
                    whiteSpace: 'nowrap',
                    fontSize: 10,
                  }}>
            {lang === 'en' ? 'EN / ع' : 'ع / EN'}
          </button>
          <button onClick={onOrder} className="btn btn--primary btn--sm">
            <span style={{width: 6, height: 6, borderRadius: '50%', background: '#fff', display: 'inline-block'}} />
            Order Direct
          </button>
        </div>
      </div>
    </header>
  );
}

// ─────────────────────────────────────────────────────────────
// Branch picker modal — fans out to platforms
// ─────────────────────────────────────────────────────────────
function BranchPicker({ open, onClose }) {
  const [step, setStep] = useState(1);
  const [branchId, setBranchId] = useState(null);
  const branch = window.DD.BRANCHES.find(b => b.id === branchId);

  useEffect(() => { if (open) { setStep(1); setBranchId(null); } }, [open]);
  useEffect(() => {
    const esc = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', esc);
    return () => window.removeEventListener('keydown', esc);
  }, [onClose]);

  if (!open) return null;

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        {/* Header */}
        <div style={{padding: '28px 36px 0 36px'}} className="flex items-start justify-between">
          <div>
            <div className="eyebrow" style={{color: 'var(--ink-3)'}}>Order Direct · Step {step} of 2</div>
            <div className="display" style={{fontSize: 36, marginTop: 6}}>
              {step === 1 ? 'Choose your branch' : 'Pick a platform'}
            </div>
          </div>
          <button onClick={onClose} style={{
            fontFamily: 'var(--sans)', fontSize: 22, color: 'var(--ink-3)',
            padding: 4, lineHeight: 1,
          }}>×</button>
        </div>

        <div style={{padding: '20px 36px 36px 36px'}}>
          <div style={{margin: '8px 0 24px 0'}}><Ornament /></div>

          {step === 1 && (
            <div className="grid gap-3">
              {window.DD.BRANCHES.map(b => (
                <button key={b.id} onClick={() => { setBranchId(b.id); setStep(2); }}
                        style={{
                          textAlign: 'left',
                          padding: '20px 22px',
                          border: '1px solid var(--rule)',
                          background: 'var(--cream)',
                          transition: 'all 160ms',
                          cursor: 'pointer',
                        }}
                        onMouseEnter={(e) => { e.currentTarget.style.borderColor = 'var(--ink)'; e.currentTarget.style.background = '#fff'; }}
                        onMouseLeave={(e) => { e.currentTarget.style.borderColor = 'var(--rule)'; e.currentTarget.style.background = 'var(--cream)'; }}>
                  <div className="flex items-start justify-between gap-4">
                    <div>
                      <div className="flex items-center gap-3">
                        <span className="display" style={{fontSize: 24}}>{b.long}</span>
                        <span className="eyebrow" style={{
                          padding: '3px 8px', border: '1px solid var(--rule)', color: 'var(--ink-3)',
                        }}>{b.flag}</span>
                      </div>
                      <div style={{color: 'var(--ink-3)', fontSize: 13, marginTop: 6}}>
                        {b.landmark} · {b.hours}
                      </div>
                      <div style={{color: 'var(--ink-3)', fontSize: 12, marginTop: 6, fontFamily: 'var(--mono)'}}>
                        Delivers: {b.delivers.join(', ')}
                      </div>
                    </div>
                    <span style={{fontFamily: 'var(--serif)', fontSize: 28, color: 'var(--ink-3)'}}>→</span>
                  </div>
                </button>
              ))}
              <div style={{marginTop: 8, fontSize: 12, color: 'var(--ink-3)'}}>
                Not sure which is closest? <a href="#" onClick={(e) => { e.preventDefault(); setBranchId('karama'); setStep(2);}} style={{borderBottom: '1px solid'}}>Use nearest to me</a>
              </div>
            </div>
          )}

          {step === 2 && branch && (
            <div>
              <div style={{padding: 16, background: 'var(--cream)', border: '1px solid var(--rule)', marginBottom: 20}}>
                <div className="flex items-center justify-between">
                  <div>
                    <div className="display" style={{fontSize: 22}}>{branch.long}</div>
                    <div style={{fontSize: 12, color: 'var(--ink-3)', marginTop: 2}}>{branch.landmark}</div>
                  </div>
                  <button onClick={() => setStep(1)} className="eyebrow" style={{color: 'var(--ink-3)'}}>Change</button>
                </div>
              </div>

              <div className="grid gap-3">
                {window.DD.PLATFORMS.map(p => {
                  const url = branch[p.id];
                  return (
                    <a key={p.id} href={url} target="_blank" rel="noopener"
                       style={{
                         display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                         padding: '20px 22px',
                         border: '1px solid var(--rule)',
                         background: p.primary ? 'var(--ink)' : 'var(--cream)',
                         color: p.primary ? '#fff' : 'var(--ink)',
                         cursor: 'pointer',
                       }}>
                      <div>
                        <div className="display" style={{fontSize: 22}}>{p.name}</div>
                        <div className="eyebrow" style={{color: p.primary ? 'rgba(255,255,255,0.7)' : 'var(--ink-3)', marginTop: 4}}>{p.tag}</div>
                      </div>
                      <span style={{fontFamily: 'var(--serif)', fontSize: 24}}>↗</span>
                    </a>
                  );
                })}

                <a href={`https://wa.me/971504511786?text=Hi%20Delhi%20Darbar%20${encodeURIComponent(branch.name)}%2C%20I'd%20like%20to%20place%20an%20order`}
                   target="_blank" rel="noopener"
                   style={{
                     padding: '14px 20px', textAlign: 'center', fontSize: 12,
                     letterSpacing: '0.16em', textTransform: 'uppercase',
                     border: '1px solid var(--rule)',
                     color: 'var(--cardamom)',
                   }}>
                  Or WhatsApp the branch directly
                </a>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Trust strip
// ─────────────────────────────────────────────────────────────
function TrustStrip({ dark }) {
  const items = [
    { big: '4.6★', small: '1,000+ ratings on Talabat' },
    { big: '40+', small: 'years in the UAE' },
    { big: '3', small: 'Dubai branches' },
    { big: '11:30–Midnight', small: 'kitchen open, daily' },
  ];
  return (
    <div style={{
      borderTop: `1px solid ${dark ? 'rgba(255,255,255,0.18)' : 'var(--rule)'}`,
      borderBottom: `1px solid ${dark ? 'rgba(255,255,255,0.18)' : 'var(--rule)'}`,
      padding: '28px 0',
      color: dark ? 'rgba(255,255,255,0.9)' : 'var(--ink)',
    }}>
      <div className="container" style={{display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 24}}>
        {items.map((it, i) => (
          <div key={i} className="flex items-baseline gap-3" style={{borderLeft: i > 0 ? `1px solid ${dark ? 'rgba(255,255,255,0.12)' : 'var(--rule)'}` : 'none', paddingLeft: i > 0 ? 24 : 0}}>
            <span className="display num" style={{fontSize: 32, lineHeight: 1}}>{it.big}</span>
            <span style={{fontSize: 12, color: dark ? 'rgba(255,255,255,0.7)' : 'var(--ink-3)', maxWidth: 160, lineHeight: 1.35}}>{it.small}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Section header — eyebrow + display + sub
// ─────────────────────────────────────────────────────────────
function SectionHeader({ no, eyebrow, title, sub, align = 'left' }) {
  return (
    <div className="flex flex-col gap-3" style={{textAlign: align, alignItems: align === 'center' ? 'center' : 'flex-start'}}>
      <div className="flex items-center gap-3">
        {no && <span style={{
          fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--ink-3)',
        }}>{no}</span>}
        <span className="eyebrow" style={{color: 'var(--ink-3)'}}>{eyebrow}</span>
      </div>
      <h2 className="display" style={{fontSize: 'clamp(36px, 5vw, 64px)', margin: 0, maxWidth: 800}}>{title}</h2>
      {sub && <p style={{fontSize: 18, color: 'var(--ink-2)', maxWidth: 640, margin: 0, lineHeight: 1.5}}>{sub}</p>}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Footer
// ─────────────────────────────────────────────────────────────
function Footer({ onOrder }) {
  return (
    <footer style={{background: 'var(--ink)', color: 'var(--ivory)', marginTop: 120}}>
      <div className="container" style={{padding: '96px 0 48px 0'}}>
        <div style={{display: 'grid', gridTemplateColumns: '1.4fr 1fr 1fr 1fr', gap: 56}}>
          <div>
            <div className="display-italic" style={{fontSize: 44, lineHeight: 1.05}}>
              Mumbai’s Best&nbsp;Biryani.<br/>
              <span className="display" style={{fontStyle: 'normal'}}>Since 1973.</span>
            </div>
            <div className="eyebrow" style={{marginTop: 18, color: 'rgba(255,255,255,0.6)'}}>In the UAE since 1984</div>
            <button onClick={onOrder} className="btn btn--ghost-light" style={{marginTop: 28}}>Order Direct →</button>
          </div>

          <div>
            <div className="eyebrow" style={{color: 'rgba(255,255,255,0.5)', marginBottom: 18}}>Branches</div>
            <div className="flex flex-col gap-3">
              {window.DD.BRANCHES.map(b => (
                <a key={b.id} href="#" onClick={(e)=>{e.preventDefault(); window.DDNav.go('branch:'+b.id);}} style={{color: '#fff'}}>
                  <div className="display" style={{fontSize: 20}}>{b.name}</div>
                  <div style={{fontSize: 12, color: 'rgba(255,255,255,0.6)', marginTop: 2}}>{b.phone}</div>
                </a>
              ))}
            </div>
          </div>

          <div>
            <div className="eyebrow" style={{color: 'rgba(255,255,255,0.5)', marginBottom: 18}}>Visit</div>
            <ul style={{listStyle: 'none', padding: 0, margin: 0}} className="flex flex-col gap-2">
              <li><a href="#" onClick={(e)=>{e.preventDefault(); window.DDNav.go('menu');}}>Menu</a></li>
              <li><a href="#" onClick={(e)=>{e.preventDefault(); window.DDNav.go('branches');}}>All branches</a></li>
              <li><a href="#" onClick={(e)=>{e.preventDefault(); window.DDNav.go('catering');}}>Catering</a></li>
              <li><a href="#" onClick={(e)=>{e.preventDefault(); window.DDNav.go('iftar');}}>Iftar packs</a></li>
              <li><a href="#" onClick={(e)=>{e.preventDefault(); window.DDNav.go('about');}}>About</a></li>
            </ul>
          </div>

          <div>
            <div className="eyebrow" style={{color: 'rgba(255,255,255,0.5)', marginBottom: 18}}>Contact</div>
            <div className="flex flex-col gap-3" style={{fontSize: 14}}>
              <a href="tel:+971504511786" style={{color: '#fff'}}>
                <div className="eyebrow" style={{color: 'rgba(255,255,255,0.5)', marginBottom: 2}}>Catering hotline</div>
                <div className="num" style={{fontSize: 18}}>+971 50 4511 786</div>
              </a>
              <a href="mailto:enquiry@delhidarbar.ae" style={{color: '#fff'}}>
                <div className="eyebrow" style={{color: 'rgba(255,255,255,0.5)', marginBottom: 2}}>Email</div>
                <div style={{fontSize: 14}}>enquiry@delhidarbar.ae</div>
              </a>
              <a href={`https://wa.me/971504511786`} target="_blank" rel="noopener" style={{color: '#fff'}}>
                <div className="eyebrow" style={{color: 'rgba(255,255,255,0.5)', marginBottom: 2}}>WhatsApp</div>
                <div style={{fontSize: 14}}>+971 50 4511 786</div>
              </a>
            </div>
          </div>
        </div>

        <div style={{marginTop: 64, paddingTop: 32, borderTop: '1px solid rgba(255,255,255,0.14)'}} className="flex items-center justify-between">
          <div style={{fontSize: 12, color: 'rgba(255,255,255,0.5)'}}>
            © 2026 Delhi Darbar UAE · Karama · Al Barsha 1 · JLT
          </div>
          <div style={{fontSize: 11, color: 'rgba(255,255,255,0.4)', fontFamily: 'var(--mono)'}}>
            Halal kitchen · No alcohol, no pork · Vegetarian menu available
          </div>
        </div>
      </div>
    </footer>
  );
}

// ─────────────────────────────────────────────────────────────
// Mobile bottom bar
// ─────────────────────────────────────────────────────────────
function MobileBar({ onOrder }) {
  return (
    <div className="mobile-bar">
      <div style={{flex: 1, fontFamily: 'var(--serif)', fontSize: 18}}>Mumbai’s Best Biryani</div>
      <button onClick={onOrder} className="btn btn--primary btn--sm">Order Direct →</button>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// WhatsApp FAB
// ─────────────────────────────────────────────────────────────
function WhatsAppFab() {
  return (
    <a href="https://wa.me/971504511786?text=Hi%20Delhi%20Darbar%2C%20I'd%20like%20a%20catering%20quote"
       target="_blank" rel="noopener"
       style={{
         position: 'fixed', bottom: 24, left: 24, zIndex: 50,
         width: 56, height: 56,
         border: '1px solid var(--ink)',
         background: 'var(--cardamom)',
         color: '#fff',
         display: 'flex', alignItems: 'center', justifyContent: 'center',
         transition: 'transform 160ms',
       }}
       onMouseEnter={(e) => { e.currentTarget.style.transform = 'scale(1.05)'; }}
       onMouseLeave={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
       title="WhatsApp: catering enquiry">
      <svg viewBox="0 0 24 24" width="24" height="24" fill="currentColor">
        <path d="M17.5 14.4c-.3-.2-1.7-.9-2-1s-.5-.2-.7.2-.8 1-.9 1.1c-.2.2-.3.2-.6 0a8 8 0 01-3.9-3.4c-.3-.5.3-.5.8-1.5.1-.2 0-.3 0-.5l-1-2.4c-.2-.5-.5-.5-.7-.5h-.6a1 1 0 00-.8.4c-.3.3-1 1-1 2.4s1 2.8 1.2 3a11 11 0 004.2 3.7c2.6 1.1 2.6.7 3.1.7.5 0 1.6-.7 1.9-1.3.2-.6.2-1.1.1-1.3l-.5-.6zM12 2a10 10 0 00-9 14.5L2 22l5.5-1.4A10 10 0 1012 2z"/>
      </svg>
    </a>
  );
}

// ─────────────────────────────────────────────────────────────
// Tag pill
// ─────────────────────────────────────────────────────────────
function Tag({ children, color = 'ink', light }) {
  const colors = {
    ink:        { bg: 'transparent', fg: 'var(--ink)', br: 'var(--rule)' },
    cardamom:   { bg: 'transparent', fg: 'var(--cardamom)', br: 'var(--cardamom)' },
    terracotta: { bg: 'var(--cta)', fg: '#fff', br: 'var(--cta)' },
    saffron:    { bg: 'var(--accent)', fg: 'var(--ink)', br: 'var(--accent)' },
    light:      { bg: 'rgba(255,255,255,0.12)', fg: '#fff', br: 'rgba(255,255,255,0.6)' },
  };
  const c = light ? colors.light : (colors[color] || colors.ink);
  return (
    <span style={{
      display: 'inline-block', padding: '3px 8px',
      fontFamily: 'var(--sans)', fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase',
      border: `1px solid ${c.br}`, background: c.bg, color: c.fg,
      whiteSpace: 'nowrap',
    }}>{children}</span>
  );
}

// ─────────────────────────────────────────────────────────────
// Open / closed indicator
// ─────────────────────────────────────────────────────────────
function OpenNow({ branch, dark }) {
  const now = new Date();
  const h = now.getHours() + now.getMinutes() / 60;
  const open = h >= branch.open.start && h < branch.open.end;
  return (
    <span className="flex items-center gap-2" style={{color: dark ? 'rgba(255,255,255,0.8)' : 'var(--ink-3)', fontSize: 12, letterSpacing: '0.04em'}}>
      <span style={{
        width: 7, height: 7, borderRadius: '50%',
        background: open ? 'var(--cardamom)' : '#c44',
        boxShadow: open ? '0 0 0 3px rgba(74,107,58,0.18)' : 'none',
        flexShrink: 0,
      }} />
      <span className="eyebrow" style={{color: 'inherit', letterSpacing: '0.16em', whiteSpace: 'nowrap'}}>{open ? 'Open now' : 'Closed'}</span>
      <span style={{color: 'inherit', opacity: 0.7, whiteSpace: 'nowrap'}}>· {branch.hours}</span>
    </span>
  );
}

// ─────────────────────────────────────────────────────────────
// Placeholder photo (for missing imagery — used as fallback too)
// ─────────────────────────────────────────────────────────────
function PhotoPlaceholder({ label, height = 360, dark, dense }) {
  const bgA = dark ? '#2a2620' : 'var(--cream-2)';
  const bgB = dark ? '#1F1B17' : 'var(--cream)';
  return (
    <div style={{
      width: '100%', height: height === 'auto' ? '100%' : height,
      background: `repeating-linear-gradient(
        135deg,
        ${bgA} 0px, ${bgA} 12px,
        ${bgB} 12px, ${bgB} 24px
      )`,
      border: dark ? '1px solid rgba(255,255,255,0.18)' : '1px solid var(--rule)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      color: dark ? 'rgba(255,255,255,0.7)' : 'var(--ink-3)',
      fontFamily: 'var(--mono)', fontSize: dense ? 9 : 11,
      letterSpacing: '0.06em', textTransform: 'uppercase',
      position: 'relative', textAlign: 'center', padding: 16,
    }}>
      [ {label} — client to supply ]
    </div>
  );
}

// SmartImg — falls back to PhotoPlaceholder if src is missing/empty/broken.
// Use everywhere instead of <img> so the design stays intact even if a photo
// goes missing.
function SmartImg({ src, label, height, style, dark, alt = '' }) {
  const [failed, setFailed] = React.useState(!src);
  React.useEffect(() => { setFailed(!src); }, [src]);
  if (failed || !src) {
    return (
      <div style={{position: 'absolute', inset: 0, ...style}}>
        <PhotoPlaceholder label={label || 'image'} height="auto" dark={dark} />
      </div>
    );
  }
  return (
    <img src={src} alt={alt}
         onError={() => setFailed(true)}
         style={{position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover', ...style}} />
  );
}

Object.assign(window, {
  Ornament, Wordmark, Nav, BranchPicker, TrustStrip, SectionHeader,
  Footer, MobileBar, WhatsAppFab, Tag, OpenNow, PhotoPlaceholder, SmartImg, fmt,
});
