/* IGI — Top Nav, Mobile Drawer, Footer, Sticky CTA, Chat Widget */

const Logo = ({ light }) => (
  <a href="#/" className="igi-logo" aria-label="IGI General Ltd">
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 10,
      color: light ? 'white' : 'var(--navy-800)',
      fontWeight: 800, fontSize: 18, letterSpacing: '-0.02em'
    }}>
      <span style={{
        width: 36, height: 36, borderRadius: 8,
        background: light ? 'white' : 'var(--navy-800)',
        color: light ? 'var(--navy-800)' : 'white',
        display: 'grid', placeItems: 'center',
        fontWeight: 800, fontSize: 13, letterSpacing: '-0.02em'
      }}>IGI</span>
      <span style={{ display: 'flex', flexDirection: 'column', lineHeight: 1 }}>
        <span style={{ fontSize: 16 }}>IGI General</span>
        <span style={{ fontSize: 10, fontWeight: 500, color: light ? 'rgba(255,255,255,.6)' : 'var(--ink-500)', letterSpacing: '0.08em', textTransform: 'uppercase', marginTop: 2 }}>Insurance · since 1953</span>
      </span>
    </span>
  </a>
);

const PRODUCTS = [
  { id: 'igi-drive', label: 'IGI Drive', icon: I.Zap, desc: 'Smart motor cover with telematics rewards', badge: 'NEW', href: 'igidrive/igi-drive.html' },
  { id: 'igi-vitality-drive', label: 'IGI Vitality Drive', icon: I.Sparkles, desc: 'Drive safer, live healthier — earn rewards', badge: 'NEW', href: 'igidrive/igi-vitality-drive.html' },
  { id: 'motor', label: 'Motor', icon: I.Car, desc: 'Private cars, commercial vehicles & bikes' },
  { id: 'home-prop', label: 'Home & Property', icon: I.Home, desc: 'Houseowner, householder & rent' },
  { id: 'travel', label: 'Travel', icon: I.Plane, desc: 'International & domestic plans' },
  { id: 'health', label: 'Health', icon: I.Heart, desc: 'Individual & family medical cover' },
  { id: 'marine', label: 'Marine', icon: I.Anchor, desc: 'Cargo, hull & freight' },
  { id: 'fire', label: 'Fire & Allied', icon: I.Flame, desc: 'Industrial, commercial & residential' },
  { id: 'engineering', label: 'Engineering', icon: I.HardHat, desc: 'CAR, EAR, machinery breakdown' },
  { id: 'liability', label: 'Liability', icon: I.Scale, desc: 'Public, product & professional' },
  { id: 'crop', label: 'Crop', icon: I.Wheat, desc: 'Yield-index & weather-based' },
  { id: 'corporate', label: 'Group / Corporate', icon: I.Building, desc: 'Tailored solutions for businesses' },
];

function Nav({ route, navigate }) {
  const [productsOpen, setProductsOpen] = React.useState(false);
  const [mobileOpen, setMobileOpen] = React.useState(false);
  const [scrolled, setScrolled] = React.useState(false);
  const [lang, setLang] = React.useState('EN');

  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 4);
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  const closeAll = () => { setProductsOpen(false); setMobileOpen(false); };

  const links = [
    { id: 'claims', label: 'Claims' },
    { id: 'locator', label: 'Find Hospital / Workshop' },
    { id: 'about', label: 'About' },
    { id: 'contact', label: 'Contact' },
  ];

  return (
    <>
      {/* Top utility bar */}
      <div style={{
        background: 'var(--navy-900)', color: 'rgba(255,255,255,.85)',
        fontSize: 12, padding: '8px 0',
      }}>
        <div className="container" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 16, flexWrap: 'wrap' }}>
          <div style={{ display: 'flex', gap: 18, alignItems: 'center' }}>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
              <I.Headset size={14} /> UAN Helpline: <strong style={{ color: 'white' }}>021-111-308-308</strong>
            </span>
            <span style={{ opacity: 0.4, display: 'inline-block' }}>·</span>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
              <I.Mail size={14} /> claims@igi.com.pk
            </span>
          </div>
          <div style={{ display: 'flex', gap: 14, alignItems: 'center' }}>
            <button onClick={() => navigate('dashboard')} style={{ color: 'white', fontSize: 12, display: 'inline-flex', alignItems: 'center', gap: 4 }}>
              <I.User size={14} /> My Account
            </button>
            <span style={{ opacity: 0.3 }}>|</span>
            <button onClick={() => setLang(lang === 'EN' ? 'اردو' : 'EN')} style={{ color: 'white', fontSize: 12, display: 'inline-flex', alignItems: 'center', gap: 4 }}>
              <I.Globe size={14} /> {lang}
            </button>
          </div>
        </div>
      </div>

      <header style={{
        position: 'sticky', top: 0, zIndex: 50,
        background: 'rgba(255,255,255,0.92)',
        backdropFilter: 'saturate(180%) blur(14px)',
        borderBottom: scrolled ? '1px solid var(--ink-200)' : '1px solid transparent',
        transition: 'border 0.2s ease',
      }}>
        <div className="container" style={{
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          padding: '14px 24px', gap: 24,
        }}>
          <Logo />

          <nav className="nav-desktop" style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
            <div
              onMouseEnter={() => setProductsOpen(true)}
              onMouseLeave={() => setProductsOpen(false)}
              style={{ position: 'relative' }}
            >
              <button style={{
                padding: '10px 14px', fontSize: 14, fontWeight: 600,
                color: 'var(--ink-700)', display: 'inline-flex', alignItems: 'center', gap: 4,
                borderRadius: 8,
              }}>
                Products <I.ChevronDown size={16} />
              </button>
              {productsOpen && (
                <div style={{
                  position: 'absolute', top: '100%', left: '50%', transform: 'translateX(-50%)',
                  paddingTop: 8, zIndex: 60,
                }}>
                <div style={{
                  width: 720, background: 'white', borderRadius: 16,
                  boxShadow: 'var(--shadow-lg)', border: '1px solid var(--ink-200)',
                  padding: 20,
                }}>
                  <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 4 }}>
                    {PRODUCTS.map(p => (
                      <button
                        key={p.id}
                        onClick={() => { if (p.href) { window.location.href = p.href; } else { navigate(p.id); } closeAll(); }}
                        style={{
                          display: 'flex', alignItems: 'flex-start', gap: 12,
                          padding: 12, borderRadius: 10, textAlign: 'left',
                          transition: 'background 0.15s ease',
                        }}
                        onMouseEnter={e => e.currentTarget.style.background = 'var(--ink-50)'}
                        onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
                      >
                        <span style={{
                          width: 36, height: 36, borderRadius: 8,
                          background: 'var(--blue-50)', color: 'var(--blue-700)',
                          display: 'grid', placeItems: 'center', flexShrink: 0,
                        }}>
                          <p.icon size={18} />
                        </span>
                        <span style={{ display: 'flex', flexDirection: 'column', gap: 2, flex: 1 }}>
                          <span style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                            <span style={{ fontSize: 14, fontWeight: 700, color: 'var(--navy-800)' }}>{p.label}</span>
                            {p.badge && <span style={{ fontSize: 9, fontWeight: 700, padding: '2px 6px', borderRadius: 4, background: 'var(--blue-600)', color: 'white', letterSpacing: '0.04em' }}>{p.badge}</span>}
                          </span>
                          <span style={{ fontSize: 12, color: 'var(--ink-500)' }}>{p.desc}</span>
                        </span>
                      </button>
                    ))}
                  </div>
                  <div style={{ marginTop: 16, paddingTop: 16, borderTop: '1px solid var(--ink-200)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <span style={{ fontSize: 13, color: 'var(--ink-500)' }}>Need help choosing? Talk to an advisor.</span>
                    <button className="btn btn-ghost btn-sm" onClick={() => { navigate('contact'); closeAll(); }}>
                      Contact us <I.ArrowRight size={14} />
                    </button>
                  </div>
                </div>
                </div>
              )}
            </div>

            {links.map(l => (
              <button
                key={l.id}
                onClick={() => navigate(l.id)}
                style={{
                  padding: '10px 14px', fontSize: 14, fontWeight: 600,
                  color: route === l.id ? 'var(--navy-800)' : 'var(--ink-700)',
                  borderRadius: 8,
                }}
              >
                {l.label}
              </button>
            ))}
          </nav>

          <div className="nav-desktop" style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
            <button className="btn btn-ghost btn-sm" onClick={() => navigate('claims')}>
              File a Claim
            </button>
            <button className="btn btn-accent btn-sm" onClick={() => navigate('quote')}>
              Get a Quote <I.ArrowRight size={14} />
            </button>
          </div>

          <button
            className="nav-mobile-toggle"
            onClick={() => setMobileOpen(true)}
            style={{ padding: 8 }}
            aria-label="Open menu"
          >
            <I.Menu size={24} />
          </button>
        </div>
      </header>

      {/* Mobile drawer */}
      {mobileOpen && (
        <div
          onClick={() => setMobileOpen(false)}
          style={{
            position: 'fixed', inset: 0, background: 'rgba(6,26,48,0.5)', zIndex: 100,
            backdropFilter: 'blur(4px)',
          }}
        >
          <div
            onClick={e => e.stopPropagation()}
            style={{
              position: 'absolute', right: 0, top: 0, bottom: 0,
              width: 'min(360px, 90vw)', background: 'white',
              padding: '20px 24px', overflowY: 'auto',
              animation: 'fadeUp 0.25s ease',
            }}
          >
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
              <Logo />
              <button onClick={() => setMobileOpen(false)} aria-label="Close menu" style={{ padding: 8 }}>
                <I.X size={22} />
              </button>
            </div>
            <div style={{ marginBottom: 16 }}>
              <div className="eyebrow" style={{ marginBottom: 8 }}>Products</div>
              {PRODUCTS.slice(0, 6).map(p => (
                <button
                  key={p.id}
                  onClick={() => { if (p.href) { window.location.href = p.href; } else { navigate(p.id); } closeAll(); }}
                  style={{
                    display: 'flex', alignItems: 'center', gap: 12,
                    padding: '10px 0', width: '100%', textAlign: 'left',
                    borderBottom: '1px solid var(--ink-100)',
                  }}
                >
                  <p.icon size={18} />
                  <span style={{ fontWeight: 600 }}>{p.label}</span>
                  <I.ChevronRight size={16} style={{ marginLeft: 'auto' }} />
                </button>
              ))}
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 4, marginBottom: 24 }}>
              {links.map(l => (
                <button
                  key={l.id}
                  onClick={() => { navigate(l.id); closeAll(); }}
                  style={{ padding: '12px 0', textAlign: 'left', fontWeight: 600, borderBottom: '1px solid var(--ink-100)' }}
                >
                  {l.label}
                </button>
              ))}
            </div>
            <button className="btn btn-accent" style={{ width: '100%' }} onClick={() => { navigate('quote'); closeAll(); }}>
              Get a Quote <I.ArrowRight size={14} />
            </button>
            <button className="btn btn-ghost" style={{ width: '100%', marginTop: 10 }} onClick={() => { navigate('claims'); closeAll(); }}>
              File a Claim
            </button>
            <div style={{ marginTop: 24, paddingTop: 16, borderTop: '1px solid var(--ink-100)', fontSize: 13, color: 'var(--ink-500)' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 6 }}>
                <I.Phone size={14} /> 021-111-308-308
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                <I.Mail size={14} /> claims@igi.com.pk
              </div>
            </div>
          </div>
        </div>
      )}
    </>
  );
}

function Footer({ navigate }) {
  return (
    <footer style={{
      background: 'var(--navy-900)', color: 'rgba(255,255,255,0.78)',
      padding: '64px 0 0', marginTop: 40,
    }}>
      <div className="container">
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))', gap: 40, paddingBottom: 48 }}>
          <div style={{ gridColumn: 'span 2', maxWidth: 360 }}>
            <Logo light />
            <p style={{ marginTop: 16, fontSize: 14, lineHeight: 1.6, color: 'rgba(255,255,255,0.7)' }}>
              Pakistan's trusted general insurer for over seven decades. We protect what matters — vehicles, homes, businesses, journeys and lives — with policies designed for clarity and claims handled with care.
            </p>
            <div style={{ display: 'flex', gap: 8, marginTop: 20 }}>
              {['AM Best', 'PACRA AA+', 'IFS Strong'].map(r => (
                <span key={r} style={{
                  fontSize: 11, fontWeight: 600, letterSpacing: '0.04em',
                  padding: '6px 10px', border: '1px solid rgba(255,255,255,0.18)',
                  borderRadius: 4, color: 'rgba(255,255,255,0.85)',
                }}>{r}</span>
              ))}
            </div>
          </div>
          <FooterCol title="Products" links={[
            ['Motor', 'motor'], ['Home & Property', 'home-prop'], ['Travel', 'travel'],
            ['Health', 'health'], ['Marine', 'marine'], ['Corporate', 'corporate'],
          ]} navigate={navigate} />
          <FooterCol title="Services" links={[
            ['Get a Quote', 'quote'], ['File a Claim', 'claims'], ['Renew Policy', 'dashboard'],
            ['Find Hospital', 'locator'], ['Find Workshop', 'locator'], ['Downloads', 'dashboard'],
          ]} navigate={navigate} />
          <FooterCol title="Company" links={[
            ['About Us', 'about'], ['Leadership', 'about'], ['Careers', 'about'],
            ['Investor Relations', 'about'], ['News & Press', 'about'], ['CSR', 'about'],
          ]} navigate={navigate} />
          <FooterCol title="Help" links={[
            ['Contact', 'contact'], ['FAQ', 'home'], ['Branch Locator', 'locator'],
            ['Complaints', 'contact'], ['Whistleblower', 'contact'],
          ]} navigate={navigate} />
        </div>

        <div style={{
          borderTop: '1px solid rgba(255,255,255,0.12)',
          padding: '24px 0', display: 'flex', justifyContent: 'space-between',
          alignItems: 'center', flexWrap: 'wrap', gap: 16, fontSize: 12,
        }}>
          <span>© 2026 IGI General Ltd. Registered with the Securities & Exchange Commission of Pakistan.</span>
          <div style={{ display: 'flex', gap: 18 }}>
            <a href="#">Privacy</a>
            <a href="#">Terms</a>
            <a href="#">Sitemap</a>
            <a href="#">Cookies</a>
          </div>
        </div>
      </div>
    </footer>
  );
}

function FooterCol({ title, links, navigate }) {
  return (
    <div>
      <div style={{
        fontSize: 12, fontWeight: 700, letterSpacing: '0.12em',
        textTransform: 'uppercase', color: 'white', marginBottom: 16,
      }}>{title}</div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {links.map(([label, route]) => (
          <button
            key={label}
            onClick={() => navigate(route)}
            style={{ textAlign: 'left', fontSize: 14, color: 'rgba(255,255,255,0.7)', padding: 0 }}
            onMouseEnter={e => e.currentTarget.style.color = 'white'}
            onMouseLeave={e => e.currentTarget.style.color = 'rgba(255,255,255,0.7)'}
          >
            {label}
          </button>
        ))}
      </div>
    </div>
  );
}

function StickyCTA({ navigate, route }) {
  const [show, setShow] = React.useState(false);
  React.useEffect(() => {
    const onScroll = () => setShow(window.scrollY > 600);
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  if (!show || route === 'quote' || route === 'dashboard') return null;
  return (
    <div className="sticky-cta">
      <I.Sparkles size={16} style={{ color: '#fbbf24' }} />
      Get a no-obligation quote in 2 minutes
      <button className="btn btn-accent" onClick={() => navigate('quote')}>
        Start <I.ArrowRight size={14} />
      </button>
    </div>
  );
}

function ChatWidget() {
  const [open, setOpen] = React.useState(false);
  const [messages, setMessages] = React.useState([
    { from: 'bot', text: 'Salam! 👋 I\'m Ayla, your IGI assistant. How can I help you today?' },
    { from: 'bot', text: 'You can ask about quotes, claims, hospital network, or policy renewal.', chips: ['Get a quote', 'Track my claim', 'Find hospital', 'Renew policy'] },
  ]);
  const [input, setInput] = React.useState('');
  const scrollRef = React.useRef();

  React.useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [messages, open]);

  const send = (text) => {
    if (!text.trim()) return;
    setMessages(m => [...m, { from: 'user', text }]);
    setInput('');
    setTimeout(() => {
      setMessages(m => [...m, {
        from: 'bot',
        text: text.toLowerCase().includes('claim')
          ? 'I can help track your claim. Please share your claim ID (format: CLM-YYYY-XXXX) or your CNIC.'
          : text.toLowerCase().includes('quote')
          ? 'Let\'s get you a quote! What would you like to insure?'
          : 'Got it. Let me connect you with the right specialist. One moment please…',
      }]);
    }, 700);
  };

  return (
    <>
      <button className="chat-fab" onClick={() => setOpen(o => !o)} aria-label="Open chat">
        {open ? <I.X size={22} /> : <I.MessageCircle size={24} />}
      </button>
      {open && (
        <div className="chat-window">
          <div style={{ background: 'var(--navy-800)', color: 'white', padding: '16px 18px', display: 'flex', alignItems: 'center', gap: 12 }}>
            <div style={{ width: 40, height: 40, borderRadius: '50%', background: 'var(--blue-500)', display: 'grid', placeItems: 'center', position: 'relative' }}>
              A
              <span style={{
                position: 'absolute', bottom: 1, right: 1, width: 10, height: 10,
                borderRadius: '50%', background: '#10b981', border: '2px solid var(--navy-800)',
              }} />
            </div>
            <div>
              <div style={{ fontSize: 14, fontWeight: 700 }}>Ayla — IGI Assistant</div>
              <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.7)' }}>Average reply time: 30s</div>
            </div>
          </div>
          <div ref={scrollRef} style={{ flex: 1, overflowY: 'auto', padding: 16, display: 'flex', flexDirection: 'column', gap: 10, background: 'var(--ink-50)' }}>
            {messages.map((m, i) => (
              <div key={i} style={{ alignSelf: m.from === 'user' ? 'flex-end' : 'flex-start', maxWidth: '80%' }}>
                <div style={{
                  padding: '10px 14px', borderRadius: 14,
                  background: m.from === 'user' ? 'var(--blue-600)' : 'white',
                  color: m.from === 'user' ? 'white' : 'var(--ink-900)',
                  fontSize: 14, lineHeight: 1.45,
                  border: m.from === 'bot' ? '1px solid var(--ink-200)' : 0,
                  borderTopLeftRadius: m.from === 'bot' ? 4 : 14,
                  borderTopRightRadius: m.from === 'user' ? 4 : 14,
                }}>{m.text}</div>
                {m.chips && (
                  <div style={{ marginTop: 8, display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                    {m.chips.map(c => (
                      <button key={c} onClick={() => send(c)} style={{
                        padding: '6px 12px', fontSize: 12, fontWeight: 600,
                        background: 'white', border: '1px solid var(--blue-100)',
                        color: 'var(--blue-700)', borderRadius: 999,
                      }}>{c}</button>
                    ))}
                  </div>
                )}
              </div>
            ))}
          </div>
          <form onSubmit={e => { e.preventDefault(); send(input); }} style={{
            padding: 12, borderTop: '1px solid var(--ink-200)', display: 'flex', gap: 8,
          }}>
            <input
              value={input}
              onChange={e => setInput(e.target.value)}
              placeholder="Type a message…"
              style={{
                flex: 1, padding: '10px 14px', border: '1px solid var(--ink-200)',
                borderRadius: 999, outline: 'none', fontSize: 14,
              }}
            />
            <button type="submit" style={{
              width: 40, height: 40, borderRadius: '50%', background: 'var(--blue-600)',
              color: 'white', display: 'grid', placeItems: 'center',
            }}><I.Send size={16} /></button>
          </form>
        </div>
      )}
    </>
  );
}

Object.assign(window, { Nav, Footer, StickyCTA, ChatWidget, Logo, PRODUCTS });
