/* Shared components: cards, marquee, navs, etc. */

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

// Format price based on currency
const fmtPrice = (p, currency) => {
  if (p === 0) return "Free";
  if (currency === "USD") return `$${Math.round(p / 83)}`;
  return `₹${p.toLocaleString("en-IN")}`;
};

// Badge config
const BADGES = {
  trending:        { label:"Trending", icon:"fire", color:"var(--primary)" },
  selling_fast:    { label:"Selling fast", icon:"bolt", color:"#f59e0b" },
  almost_sold_out: { label:"Almost sold out", icon:"bolt", color:"#dc2626" },
  free:            { label:"Free", icon:"sparkle", color:"#10b981" },
  new:             { label:"New", icon:"sparkle", color:"#06b6d4" },
};

// Marquee for ticker tape brand
const Marquee = ({ items, speed=40 }) => (
  <div style={{ overflow:"hidden", whiteSpace:"nowrap", display:"flex" }}>
    <div style={{ display:"inline-flex", gap:24, animation:`marquee ${speed}s linear infinite` }}>
      {[...items, ...items, ...items].map((item, i) => (
        <span key={i} style={{ display:"inline-flex", alignItems:"center", gap:8, color:"var(--ink-3)", fontFamily:"var(--font-mono)", fontSize:11, letterSpacing:"0.06em", textTransform:"uppercase" }}>
          {item}<span style={{ color:"var(--primary)" }}>●</span>
        </span>
      ))}
    </div>
  </div>
);

// Logo wordmark
const Logo = ({ small }) => (
  <div style={{ display:"flex", alignItems:"center", gap:8 }}>
    <div style={{
      width: small?22:28, height: small?22:28, borderRadius: 6,
      background: "var(--primary)", color:"var(--ink-on-primary)",
      display:"flex", alignItems:"center", justifyContent:"center",
      fontFamily:"var(--font-mono)", fontWeight:700, fontSize: small?12:14,
      position:"relative", overflow:"hidden",
    }}>
      <span style={{ position:"relative", zIndex:1 }}>TT</span>
      <span style={{ position:"absolute", left:0, top:"50%", transform:"translateY(-50%)", width:"100%", height:1, background:"rgba(255,255,255,0.4)" }} />
    </div>
    <span className="t-display" style={{ fontSize: small?15:18, fontWeight:700, letterSpacing:"-0.02em" }}>
      Ticket<span style={{ color:"var(--primary)" }}>Tape</span>
    </span>
  </div>
);

// Card variants
const EventCard = ({ event, variant, onClick, currency, dense, friends }) => {
  const [saved, setSaved] = useState(false);
  const [loaded, setLoaded] = useState(false);
  const badge = event.badge ? BADGES[event.badge] : null;
  const v = variant || "rich";

  // Editorial — magazine-style
  if (v === "editorial") {
    return (
      <div onClick={onClick} style={{ cursor:"pointer", display:"flex", flexDirection:"column", gap:12, paddingBottom:18, borderBottom:"1px solid var(--line)" }}>
        <div style={{ position:"relative", aspectRatio:"4/5", borderRadius:"var(--radius)", overflow:"hidden", background:"var(--surface)" }}>
          <img src={event.image} alt="" onLoad={()=>setLoaded(true)} style={{ width:"100%", height:"100%", objectFit:"cover", opacity:loaded?1:0, transition:"opacity .4s" }} />
          {badge && (
            <div style={{ position:"absolute", top:10, left:10, padding:"4px 10px", background:"var(--bg)", color:"var(--ink)", borderRadius:999, fontSize:10, fontFamily:"var(--font-mono)", textTransform:"uppercase", letterSpacing:"0.1em", display:"inline-flex", alignItems:"center", gap:5 }}>
              <I.fire cls="ico-sm" /><span style={{ color: badge.color }}>{badge.label}</span>
            </div>
          )}
          <button onClick={e=>{e.stopPropagation();setSaved(s=>!s);}} className="icon-btn" style={{ position:"absolute", top:10, right:10, color: saved?"var(--primary)":"#fff" }}>
            <I.heart cls="ico-sm" />
          </button>
        </div>
        <div className="t-eyebrow">{event.tag}</div>
        <h3 className="t-display" style={{ fontSize: dense==="compact"?17:21, lineHeight:1.1 }}>{event.title}</h3>
        <div style={{ display:"flex", gap:12, color:"var(--ink-2)", fontSize:12 }}>
          <span className="t-mono">{event.date}</span>
          <span style={{ color:"var(--ink-3)" }}>·</span>
          <span>{event.area}</span>
        </div>
        <div style={{ display:"flex", justifyContent:"space-between", alignItems:"center", marginTop:4 }}>
          <span className="t-mono" style={{ fontSize:14, fontWeight:600 }}>{event.price === 0 ? "FREE" : `from ${fmtPrice(event.price, currency)}`}</span>
          {friends && event.friends > 0 && (
            <span style={{ fontSize:11, color:"var(--ink-3)" }}>{event.friends} friends going</span>
          )}
        </div>
      </div>
    );
  }

  // Compact — dense list-friendly
  if (v === "compact") {
    return (
      <div onClick={onClick} style={{ cursor:"pointer", display:"flex", gap:12, padding:"10px 0", borderBottom:"1px solid var(--line)" }}>
        <div style={{ width:88, height:88, borderRadius:"var(--radius-sm)", overflow:"hidden", flexShrink:0, background:"var(--surface)", position:"relative" }}>
          <img src={event.image} alt="" style={{ width:"100%", height:"100%", objectFit:"cover" }} />
          {badge && (() => { const BIcon = I[badge.icon]; return (
            <div style={{ position:"absolute", top:4, left:4, width:18, height:18, borderRadius:6, background: badge.color, display:"flex", alignItems:"center", justifyContent:"center", color:"#fff" }}><BIcon cls="ico-sm" /></div>
          ); })()}
        </div>
        <div style={{ flex:1, minWidth:0, display:"flex", flexDirection:"column", justifyContent:"center", gap:4 }}>
          <div className="t-eyebrow" style={{ fontSize:9 }}>{event.category}</div>
          <h3 style={{ fontSize:14, fontWeight:600, color:"var(--ink)", overflow:"hidden", textOverflow:"ellipsis", display:"-webkit-box", WebkitLineClamp:2, WebkitBoxOrient:"vertical" }}>{event.title}</h3>
          <div className="t-mono" style={{ fontSize:11, color:"var(--ink-3)" }}>{event.date} · {event.time}</div>
          <div style={{ fontSize:11, color:"var(--ink-3)", overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap" }}>{event.venue}</div>
        </div>
        <div style={{ display:"flex", flexDirection:"column", alignItems:"flex-end", justifyContent:"space-between" }}>
          <button onClick={e=>{e.stopPropagation();setSaved(s=>!s);}} style={{ color: saved?"var(--primary)":"var(--ink-3)", padding:4 }}>
            <I.heart cls="ico-sm" />
          </button>
          <span className="t-mono" style={{ fontSize:13, fontWeight:600 }}>{fmtPrice(event.price, currency)}</span>
        </div>
      </div>
    );
  }

  // Rich (default) — image-led card
  return (
    <div onClick={onClick} className="card" style={{ cursor:"pointer", transition:"transform var(--dur) var(--ease), box-shadow var(--dur) var(--ease)" }}
      onMouseEnter={e=>{e.currentTarget.style.transform="translateY(-3px)"; e.currentTarget.style.boxShadow="0 18px 40px rgba(0,0,0,0.3)"}}
      onMouseLeave={e=>{e.currentTarget.style.transform=""; e.currentTarget.style.boxShadow=""}}
    >
      <div style={{ position:"relative", aspectRatio:"5/4", overflow:"hidden", background:"var(--surface-2)" }}>
        <img src={event.image} alt="" onLoad={()=>setLoaded(true)} style={{ width:"100%", height:"100%", objectFit:"cover", opacity:loaded?1:0, transition:"opacity .4s" }} />
        {badge && (
          <div style={{ position:"absolute", top:10, left:10, padding:"4px 10px", background: badge.color, color:"#fff", borderRadius:999, fontSize:10, fontFamily:"var(--font-mono)", textTransform:"uppercase", letterSpacing:"0.08em", fontWeight:600 }}>
            {badge.label}
          </div>
        )}
        <button onClick={e=>{e.stopPropagation();setSaved(s=>!s);}} className="icon-btn" style={{ position:"absolute", top:10, right:10, color: saved?"var(--primary)":"#fff" }}>
          <I.heart cls="ico-sm" />
        </button>
        {friends && event.friends > 0 && (
          <div style={{ position:"absolute", bottom:10, left:10, display:"flex", alignItems:"center", gap:6, padding:"4px 10px 4px 4px", background:"rgba(0,0,0,0.55)", backdropFilter:"blur(8px)", borderRadius:999, color:"#fff", fontSize:11 }}>
            <div style={{ display:"flex" }}>
              {DATA.friends.slice(0, Math.min(3, event.friends)).map((f, i) => (
                <div key={i} style={{ width:18, height:18, borderRadius:"50%", background:f.color, marginLeft:i?-6:0, border:"1.5px solid #000", fontSize:9, fontWeight:700, display:"flex", alignItems:"center", justifyContent:"center" }}>{f.initial}</div>
              ))}
            </div>
            <span>{event.friends} going</span>
          </div>
        )}
      </div>
      <div style={{ padding:"14px 14px 14px" }}>
        <div className="t-eyebrow" style={{ marginBottom:6 }}>{event.tag}</div>
        <h3 style={{ fontSize: dense==="compact"?14:15, fontWeight:600, lineHeight:1.3, marginBottom:8, display:"-webkit-box", WebkitLineClamp:2, WebkitBoxOrient:"vertical", overflow:"hidden" }}>{event.title}</h3>
        <div style={{ display:"flex", flexDirection:"column", gap:3, color:"var(--ink-2)", fontSize:12 }}>
          <div style={{ display:"flex", alignItems:"center", gap:6 }}><I.calendar cls="ico-sm" /><span className="t-mono">{event.date} · {event.time}</span></div>
          <div style={{ display:"flex", alignItems:"center", gap:6 }}><I.pin cls="ico-sm" /><span style={{ overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap" }}>{event.venue}</span></div>
        </div>
        <div style={{ marginTop:10, paddingTop:10, borderTop:"1px solid var(--line)", display:"flex", justifyContent:"space-between", alignItems:"center" }}>
          <span className="t-mono" style={{ fontSize:14, fontWeight:600, color: event.price===0?"#10b981":"var(--ink)" }}>
            {event.price === 0 ? "FREE" : `from ${fmtPrice(event.price, currency)}`}
          </span>
          <span style={{ background:"var(--primary)", color:"var(--ink-on-primary)", padding:"5px 12px", borderRadius:999, fontSize:11, fontWeight:600 }}>Book</span>
        </div>
      </div>
    </div>
  );
};

// Bottom navigation (mobile)
const BottomNav = ({ active, onNav }) => {
  const items = [
    { id:"home", label:"Home", icon:"home" },
    { id:"search", label:"Discover", icon:"search" },
    { id:"map", label:"Nearby", icon:"map" },
    { id:"tickets", label:"Tickets", icon:"ticket" },
    { id:"profile", label:"You", icon:"user" },
  ];
  return (
    <div style={{ position:"absolute", bottom:0, left:0, right:0, background:"color-mix(in oklab, var(--bg) 92%, transparent)", backdropFilter:"blur(20px)", borderTop:"1px solid var(--line)", padding:"10px 8px 14px", display:"flex", justifyContent:"space-around", zIndex:50 }}>
      {items.map(item => {
        const Icon = I[item.icon];
        const isActive = active === item.id;
        return (
          <button key={item.id} onClick={()=>onNav(item.id)} style={{ display:"flex", flexDirection:"column", alignItems:"center", gap:4, color: isActive?"var(--primary)":"var(--ink-3)", padding:"4px 8px" }}>
            <Icon />
            <span style={{ fontSize:9.5, fontWeight: isActive?600:500, letterSpacing:"0.02em" }}>{item.label}</span>
          </button>
        );
      })}
    </div>
  );
};

// Top app bar (mobile)
const MobileTopBar = ({ city, onCityClick, onAI }) => (
  <div style={{ display:"flex", justifyContent:"space-between", alignItems:"center", padding:"14px 18px 10px" }}>
    <button onClick={onCityClick} style={{ display:"flex", alignItems:"center", gap:6, color:"var(--ink)" }}>
      <I.pin cls="ico-sm" />
      <span style={{ fontWeight:600, fontSize:14 }}>{city}</span>
      <span style={{ fontSize:10, color:"var(--ink-3)" }}>▾</span>
    </button>
    <div style={{ display:"flex", alignItems:"center", gap:6 }}>
      <button onClick={onAI} style={{ width:36, height:36, borderRadius:"50%", background:"var(--surface)", display:"flex", alignItems:"center", justifyContent:"center", color:"var(--primary)", border:"1px solid var(--line)" }}>
        <I.sparkle cls="ico-sm" />
      </button>
      <button style={{ width:36, height:36, borderRadius:"50%", background:"var(--surface)", display:"flex", alignItems:"center", justifyContent:"center", color:"var(--ink)", border:"1px solid var(--line)" }}>
        <I.bell cls="ico-sm" />
      </button>
    </div>
  </div>
);

// Desktop nav
const DesktopNav = ({ active, onNav, onAI }) => (
  <header style={{ position:"sticky", top:0, zIndex:100, background:"color-mix(in oklab, var(--bg) 92%, transparent)", backdropFilter:"blur(20px)", borderBottom:"1px solid var(--line)" }}>
    <div style={{ maxWidth:1180, margin:"0 auto", padding:"14px 28px", display:"flex", alignItems:"center", gap:32 }}>
      <Logo />
      <div style={{ display:"flex", alignItems:"center", gap:4, marginLeft:8 }}>
        {[
          { id:"home", label:"Discover" },
          { id:"search", label:"Browse" },
          { id:"map", label:"Map" },
          { id:"organiser", label:"For Organisers" },
        ].map(it => (
          <button key={it.id} onClick={()=>onNav(it.id)} style={{ padding:"7px 14px", borderRadius:999, fontSize:13, fontWeight:500, color: active===it.id?"var(--ink)":"var(--ink-2)", background: active===it.id?"var(--surface)":"transparent" }}>
            {it.label}
          </button>
        ))}
      </div>
      <div style={{ flex:1, maxWidth:420, position:"relative" }}>
        <button onClick={()=>onNav("search")} style={{ width:"100%", display:"flex", alignItems:"center", gap:10, padding:"9px 14px", background:"var(--surface)", border:"1px solid var(--line)", borderRadius:999, color:"var(--ink-3)", fontSize:13, textAlign:"left" }}>
          <I.search cls="ico-sm" />
          <span>Search events, artists, venues…</span>
          <span style={{ marginLeft:"auto", padding:"2px 6px", background:"var(--surface-2)", borderRadius:6, fontSize:10, fontFamily:"var(--font-mono)" }}>⌘K</span>
        </button>
      </div>
      <button onClick={onAI} className="btn btn-ghost" style={{ padding:"7px 14px", display:"flex", alignItems:"center", gap:6 }}>
        <I.sparkle cls="ico-sm" />
        <span style={{ fontSize:12 }}>Ask AI</span>
      </button>
      <button onClick={()=>onNav("tickets")} style={{ position:"relative", color:"var(--ink-2)", padding:8 }}><I.ticket /><span style={{ position:"absolute", top:4, right:2, width:8, height:8, borderRadius:"50%", background:"var(--primary)" }} /></button>
      <button onClick={()=>onNav("profile")} style={{ width:34, height:34, borderRadius:"50%", background:"linear-gradient(135deg, var(--primary), color-mix(in oklab, var(--primary) 60%, #000))", color:"#fff", fontWeight:700, fontSize:13 }}>A</button>
    </div>
  </header>
);

// Section header
const Section = ({ title, eyebrow, action, onAction, children, dense }) => (
  <section style={{ margin: dense==="compact"?"24px 0":dense==="cozy"?"40px 0":"32px 0" }}>
    <div style={{ display:"flex", justifyContent:"space-between", alignItems:"flex-end", marginBottom:14, padding:"0 18px" }}>
      <div>
        {eyebrow && <div className="t-eyebrow" style={{ marginBottom:4 }}>{eyebrow}</div>}
        <h2 className="t-display" style={{ fontSize:18 }}>{title}</h2>
      </div>
      {action && <button onClick={onAction} className="t-mono" style={{ fontSize:11, color:"var(--ink-3)", textTransform:"uppercase", letterSpacing:"0.1em" }}>{action} →</button>}
    </div>
    {children}
  </section>
);

window.fmtPrice = fmtPrice;
window.BADGES = BADGES;
window.Marquee = Marquee;
window.Logo = Logo;
window.EventCard = EventCard;
window.BottomNav = BottomNav;
window.MobileTopBar = MobileTopBar;
window.DesktopNav = DesktopNav;
window.Section = Section;
