// Branch Finder — the centerpiece. List + map, all 12 outlets, real deep-links.
const { useState: useStateBranch, useMemo: useMemoBranch, useEffect: useEffectBranch } = React;

function PageBranches({ navigate }) {
  const [selected, setSelected] = useStateBranch(null);
  const [emirate, setEmirate] = useStateBranch('all');
  const [format, setFormat] = useStateBranch('all');
  const [query, setQuery] = useStateBranch('');

  const filtered = useMemoBranch(() => {
    return window.BRANCHES.filter(b => {
      if (emirate !== 'all' && b.emirate !== emirate) return false;
      if (format !== 'all' && b.format !== format) return false;
      if (query) {
        const q = query.toLowerCase();
        if (!(b.name + ' ' + b.address + ' ' + b.sub).toLowerCase().includes(q)) return false;
      }
      return true;
    });
  }, [emirate, format, query]);

  const selectedBranch = window.BRANCHES.find(b => b.id === selected);

  return (
    <main className="fade-enter">
      <BranchHero filtered={filtered} />

      <section style={{ padding: '32px 0 96px' }}>
        <div className="container container--wide">
          <BranchFilters
            emirate={emirate} setEmirate={setEmirate}
            format={format} setFormat={setFormat}
            query={query} setQuery={setQuery}
            count={filtered.length}
          />

          <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 32, marginTop: 32 }} className="branch-layout">
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 16, alignContent: 'start' }}>
              {filtered.length === 0 && (
                <div style={{ gridColumn: '1 / -1', padding: 40, textAlign: 'center', background: 'var(--cream)', borderRadius: 'var(--radius)' }}>
                  <div className="serif" style={{ fontSize: 22, color: 'var(--charcoal)' }}>No branches match that filter.</div>
                  <div style={{ fontSize: 14, color: 'var(--ink-2)', marginTop: 8 }}>Try clearing the search or picking a different emirate.</div>
                </div>
              )}
              {filtered.map(b => (
                <BranchCard
                  key={b.id}
                  branch={b}
                  selected={selected === b.id}
                  onSelect={setSelected}
                />
              ))}
            </div>

            <aside style={{ position: 'sticky', top: 200, alignSelf: 'start', display: 'flex', flexDirection: 'column', gap: 16 }}>
              <UAEMap branches={filtered} selectedId={selected} onSelect={setSelected} />
              <BranchDetailCard branch={selectedBranch} />
            </aside>
          </div>
        </div>
      </section>

      <style>{`
        @media (max-width: 960px) {
          .branch-layout { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </main>
  );
}

function BranchHero({ filtered }) {
  return (
    <section style={{ background: 'var(--cream)', padding: '64px 0 32px', borderBottom: '1px solid var(--line)' }}>
      <div className="container container--wide">
        <div style={{ display: 'flex', alignItems: 'end', justifyContent: 'space-between', gap: 24, flexWrap: 'wrap' }}>
          <div>
            <div className="eyebrow">Branch finder</div>
            <h1 style={{ fontSize: 'clamp(40px, 5vw, 64px)', lineHeight: 1.05, marginTop: 14 }}>
              Every charcoal grill in the UAE.
            </h1>
            <p className="lede" style={{ marginTop: 16 }}>
              12 outlets across Dubai &amp; Abu Dhabi. Tap a card to see hours, route, and deep-link to your delivery app of choice.
            </p>
          </div>
          <div style={{ display: 'flex', gap: 16, fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--ink-2)', letterSpacing: '0.08em' }}>
            <div><span style={{ color: 'var(--terracotta)', fontSize: 32, fontFamily: 'var(--font-serif)' }}>9</span> Dubai</div>
            <div><span style={{ color: 'var(--terracotta)', fontSize: 32, fontFamily: 'var(--font-serif)' }}>3</span> Abu Dhabi</div>
            <div><span style={{ color: 'var(--terracotta)', fontSize: 32, fontFamily: 'var(--font-serif)' }}>0</span> N. Emirates</div>
          </div>
        </div>
      </div>
    </section>
  );
}

function BranchFilters({ emirate, setEmirate, format, setFormat, query, setQuery, count }) {
  return (
    <div style={{
      display: 'flex',
      gap: 16,
      alignItems: 'center',
      flexWrap: 'wrap',
      padding: '20px 24px',
      background: 'var(--paper)',
      border: '1px solid var(--line)',
      borderRadius: 999,
    }}>
      <Pill label="EMIRATE">
        {[['all','All'],['Dubai','Dubai'],['Abu Dhabi','Abu Dhabi']].map(([v,l]) => (
          <PillButton key={v} active={emirate===v} onClick={() => setEmirate(v)}>{l}</PillButton>
        ))}
      </Pill>
      <div style={{ width: 1, height: 24, background: 'var(--line)' }} />
      <Pill label="FORMAT">
        {[['all','All'],['restaurant','Restaurant'],['foodcourt','Food court'],['delivery','Delivery']].map(([v,l]) => (
          <PillButton key={v} active={format===v} onClick={() => setFormat(v)}>{l}</PillButton>
        ))}
      </Pill>
      <div style={{ width: 1, height: 24, background: 'var(--line)' }} />
      <div style={{ position: 'relative', flex: 1, minWidth: 200 }}>
        <Icon.search width="14" height="14" style={{ position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)', color: 'var(--ink-3)' }} />
        <input
          placeholder="Search by name or address"
          value={query}
          onChange={e => setQuery(e.target.value)}
          style={{
            width: '100%', padding: '8px 12px 8px 32px',
            border: 'none', background: 'transparent',
            fontFamily: 'var(--font-sans)', fontSize: 13,
            outline: 'none',
          }}
        />
      </div>
      <div className="mono" style={{ fontSize: 11, color: 'var(--ink-3)', letterSpacing: '0.1em' }}>
        {count} / 12 OUTLETS
      </div>
    </div>
  );
}

function Pill({ label, children }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
      <span className="mono" style={{ fontSize: 10, letterSpacing: '0.14em', color: 'var(--ink-3)' }}>{label}</span>
      <div style={{ display: 'flex', gap: 4 }}>{children}</div>
    </div>
  );
}
function PillButton({ active, onClick, children }) {
  return (
    <button onClick={onClick} style={{
      padding: '5px 11px', borderRadius: 999,
      background: active ? 'var(--charcoal)' : 'transparent',
      color: active ? 'var(--paper)' : 'var(--ink-2)',
      fontSize: 12, fontWeight: active ? 600 : 500,
      transition: 'background .12s',
    }}>{children}</button>
  );
}

function UAEMap({ branches, selectedId, onSelect }) {
  return (
    <div style={{
      borderRadius: 'var(--radius)',
      overflow: 'hidden',
      border: '1px solid var(--line)',
      position: 'relative',
      aspectRatio: '4/3',
    }}>
      <LeafletMap branches={branches} selectedId={selectedId} onSelect={onSelect} defaultCenter={[25.0, 54.8]} defaultZoom={9} />
      <div style={{
        position: 'absolute', top: 12, left: 12, zIndex: 500,
        background: 'var(--paper)', borderRadius: 999, padding: '6px 12px',
        fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.1em',
        color: 'var(--ink-2)',
        boxShadow: '0 2px 6px rgba(31,27,23,0.06)',
      }}>
        UAE · 12 OUTLETS
      </div>
      <div style={{
        position: 'absolute', bottom: 12, left: 12, zIndex: 500,
        display: 'flex', gap: 12, alignItems: 'center',
        fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--ink-2)',
        background: 'rgba(255,252,246,0.9)', padding: '6px 10px', borderRadius: 999,
        backdropFilter: 'blur(6px)',
      }}>
        <span style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
          <span style={{ width: 8, height: 8, background: 'var(--terracotta)', borderRadius: '50%' }} /> Active
        </span>
        <span style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
          <span style={{ width: 8, height: 8, background: '#A89678', borderRadius: '50%' }} /> Filtered out
        </span>
      </div>
    </div>
  );
}


function BranchDetailCard({ branch }) {
  if (!branch) {
    return (
      <div style={{
        background: 'var(--cream)',
        border: '1px dashed var(--line-strong)',
        borderRadius: 'var(--radius)',
        padding: 28,
        textAlign: 'center',
      }}>
        <div style={{ fontSize: 28, marginBottom: 8 }}>📍</div>
        <div className="serif" style={{ fontSize: 18, color: 'var(--charcoal)' }}>Tap a branch on the map</div>
        <div style={{ fontSize: 13, color: 'var(--ink-2)', marginTop: 6 }}>Hours, route and deep-links will appear here.</div>
      </div>
    );
  }
  return (
    <div style={{
      background: 'var(--charcoal)',
      color: 'var(--paper)',
      borderRadius: 'var(--radius)',
      padding: 24,
    }}>
      <div className="mono" style={{ fontSize: 10, letterSpacing: '0.14em', color: 'var(--saffron)' }}>{branch.emirate.toUpperCase()}</div>
      <div className="serif" style={{ fontSize: 24, color: 'var(--paper)', marginTop: 8 }}>{branch.name}</div>
      <div style={{ fontSize: 13, color: 'rgba(245,235,220,0.7)', marginTop: 4 }}>{branch.sub}</div>
      <hr style={{ border: 'none', borderTop: '1px solid rgba(245,235,220,0.15)', margin: '20px 0' }} />
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12, fontSize: 13, color: 'rgba(245,235,220,0.85)' }}>
        <div style={{ display: 'flex', gap: 10, alignItems: 'start' }}>
          <Icon.pin width="14" height="14" style={{ marginTop: 2, color: 'var(--saffron)', flexShrink: 0 }} />
          <span>{branch.address}</span>
        </div>
        <div style={{ display: 'flex', gap: 10, alignItems: 'start' }}>
          <Icon.clock width="14" height="14" style={{ marginTop: 2, color: 'var(--saffron)', flexShrink: 0 }} />
          <span>{branch.hours}</span>
        </div>
        <div style={{ display: 'flex', gap: 10, alignItems: 'start' }}>
          <Icon.phone width="14" height="14" style={{ marginTop: 2, color: 'var(--saffron)', flexShrink: 0 }} />
          <a href={`tel:${branch.phone.replace(/\s/g,'')}`} style={{ color: 'var(--paper)' }}>{branch.phone}</a>
        </div>
      </div>
      <div style={{ marginTop: 20, display: 'flex', gap: 8, flexWrap: 'wrap' }}>
        <a className="btn btn--primary btn--sm" href={branch.deeplinks.talabat || '#'} target="_blank" rel="noopener">
          Order →
        </a>
        <a className="btn btn--ghost-light btn--sm" href={`https://www.google.com/maps?q=${encodeURIComponent(branch.address)}`} target="_blank" rel="noopener">
          Directions
        </a>
      </div>
    </div>
  );
}

window.PageBranches = PageBranches;
