/* Search, Map, Calendar screens */

const { useState, useMemo } = React;

// ─── SEARCH / DISCOVER ────────────────────────────────────────────
const SearchScreen = ({ tweaks, isMobile, nav, initialFilters }) => {
  const cardVariant = tweaks.cardStyle || "rich";
  const dense = tweaks.density || "comfortable";
  const currency = tweaks.currency || "INR";
  const friends = tweaks.showFriends !== false;
  const [q, setQ] = useState("");
  const [filters, setFilters] = useState(initialFilters || { category:null, when:null, price:null });

  const results = useMemo(() => {
    let r = DATA.events;
    if (q) r = r.filter(e => e.title.toLowerCase().includes(q.toLowerCase()) || e.tag.toLowerCase().includes(q.toLowerCase()));
    if (filters.category) r = r.filter(e => e.category === filters.category);
    if (filters.when === "tonight") r = r.filter(e => e.date === "13 Jun");
    if (filters.when === "weekend") r = r.filter(e => ["14 Jun","15 Jun"].includes(e.date));
    if (filters.price === "free") r = r.filter(e => e.price === 0);
    if (filters.price === "paid") r = r.filter(e => e.price > 0);
    return r;
  }, [q, filters]);

  return (
    <div>
      {/* Search bar */}
      <div style={{ padding: isMobile?"14px 18px":"24px 28px", borderBottom:"1px solid var(--line)", position:"sticky", top: isMobile?0:65, background:"color-mix(in oklab, var(--bg) 95%, transparent)", backdropFilter:"blur(20px)", zIndex:50 }}>
        <div style={{ position:"relative" }}>
          <input value={q} onChange={e=>setQ(e.target.value)} placeholder="Search events, artists, venues…" style={{ width:"100%", padding:"12px 14px 12px 38px", background:"var(--surface)", border:"1px solid var(--line)", borderRadius:"var(--radius)", color:"var(--ink)", fontSize:14, outline:"none", fontFamily:"inherit" }} />
          <span style={{ position:"absolute", left:14, top:"50%", transform:"translateY(-50%)", color:"var(--ink-3)", pointerEvents:"none", display:"flex" }}><I.search cls="ico-sm" /></span>
        </div>
        {/* Filter chips */}
        <div style={{ display:"flex", gap:8, marginTop:12, overflowX:"auto", paddingBottom:2 }}>
          {[
            { key:"when", val:"tonight", label:"Tonight" },
            { key:"when", val:"weekend", label:"This weekend" },
            { key:"price", val:"free", label:"Free" },
            { key:"price", val:"paid", label:"Paid" },
            ...DATA.categories.slice(0,5).map(c => ({ key:"category", val:c.label, label:c.label })),
          ].map((c, i) => {
            const active = filters[c.key] === c.val;
            return (
              <button key={i} onClick={()=>setFilters(f=>({...f, [c.key]: active?null:c.val }))} style={{ flexShrink:0, padding:"6px 14px", borderRadius:999, background: active?"var(--ink)":"var(--surface)", color: active?"var(--bg)":"var(--ink-2)", border:`1px solid ${active?"var(--ink)":"var(--line)"}`, fontSize:12, fontWeight: active?600:500 }}>{c.label}</button>
            );
          })}
        </div>
      </div>

      <div style={{ padding: isMobile?"16px 18px":"28px", maxWidth:1180, margin:"0 auto" }}>
        <div style={{ display:"flex", justifyContent:"space-between", alignItems:"baseline", marginBottom:18 }}>
          <h2 className="t-display" style={{ fontSize:20 }}>{results.length} events</h2>
          <span className="t-mono" style={{ fontSize:11, color:"var(--ink-3)", textTransform:"uppercase" }}>Sorted by relevance</span>
        </div>
        {results.length === 0 ? (
          <div style={{ textAlign:"center", padding:"60px 20px", color:"var(--ink-3)" }}>
            <div style={{ fontSize:32, marginBottom:12 }}>○</div>
            <div>No events match your filters.</div>
          </div>
        ) : (
          <div style={{ display:"grid", gridTemplateColumns: isMobile?"repeat(2,1fr)":"repeat(3,1fr)", gap: isMobile?12:18 }}>
            {results.map(ev => (
              <EventCard key={ev.id} event={ev} variant={cardVariant} dense={dense} currency={currency} friends={friends} onClick={()=>nav("detail", ev.id)} />
            ))}
          </div>
        )}
      </div>
      <div style={{ height: isMobile?100:40 }} />
    </div>
  );
};

// ─── MAP / NEARBY ─────────────────────────────────────────────────
const MapScreen = ({ tweaks, isMobile, nav }) => {
  const currency = tweaks.currency || "INR";
  const [selected, setSelected] = useState(DATA.events[0].id);
  const ev = DATA.events.find(e => e.id === selected);

  return (
    <div style={{ position:"relative", height: isMobile?"100%":"calc(100vh - 64px)", overflow:"hidden" }}>
      {/* Map background — stylized SVG grid */}
      <div style={{ position:"absolute", inset:0, background: tweaks.theme==="light" ? "#e8eef2" : "#0a1014" }}>
        <svg viewBox="0 0 800 800" style={{ width:"100%", height:"100%", opacity:0.6 }}>
          <defs>
            <pattern id="grid" width="40" height="40" patternUnits="userSpaceOnUse">
              <path d="M 40 0 L 0 0 0 40" fill="none" stroke={tweaks.theme==="light"?"#cdd6dc":"#1a242c"} strokeWidth="0.5" />
            </pattern>
          </defs>
          <rect width="800" height="800" fill="url(#grid)" />
          {/* Stylized streets */}
          <path d="M 0 200 Q 200 150, 400 220 T 800 200" stroke={tweaks.theme==="light"?"#a8b5be":"#293641"} strokeWidth="3" fill="none" />
          <path d="M 100 0 Q 150 300, 300 500 T 400 800" stroke={tweaks.theme==="light"?"#a8b5be":"#293641"} strokeWidth="3" fill="none" />
          <path d="M 0 500 Q 300 480, 600 540 T 800 500" stroke={tweaks.theme==="light"?"#a8b5be":"#293641"} strokeWidth="3" fill="none" />
          <path d="M 600 0 L 580 800" stroke={tweaks.theme==="light"?"#a8b5be":"#293641"} strokeWidth="2" fill="none" />
          {/* Water/park areas */}
          <ellipse cx="650" cy="650" rx="120" ry="80" fill={tweaks.theme==="light"?"#c2d3dc":"#0d1820"} />
          <ellipse cx="180" cy="680" rx="90" ry="60" fill={tweaks.theme==="light"?"#c8dccc":"#0e1a13"} />
          {/* Neighborhood labels */}
          {[
            { x:150, y:280, name:"BANDRA" },
            { x:480, y:340, name:"COLABA" },
            { x:340, y:560, name:"WORLI" },
            { x:620, y:200, name:"ANDHERI" },
          ].map(n => (
            <text key={n.name} x={n.x} y={n.y} fill={tweaks.theme==="light"?"#7a8993":"#3a4854"} fontSize="11" fontFamily="ui-monospace, monospace" letterSpacing="2">{n.name}</text>
          ))}
        </svg>
        {/* Pins */}
        {DATA.events.slice(0, 14).map((e, i) => {
          const positions = [
            [25,40],[55,30],[40,55],[70,25],[20,65],[50,70],[80,50],[35,35],
            [60,60],[15,30],[75,75],[45,15],[30,80],[65,45],
          ];
          const [x,y] = positions[i % positions.length];
          const isSel = selected === e.id;
          return (
            <button key={e.id} onClick={()=>setSelected(e.id)} style={{
              position:"absolute", left:`${x}%`, top:`${y}%`, transform:"translate(-50%, -100%)",
              transition:"transform var(--dur) var(--ease)", zIndex: isSel?20:10,
            }}>
              <div style={{
                padding: isSel?"6px 12px":"4px 10px",
                background: isSel?"var(--primary)":"var(--bg)",
                color: isSel?"var(--ink-on-primary)":"var(--ink)",
                borderRadius:999,
                border:`2px solid ${isSel?"var(--primary)":"var(--line-strong)"}`,
                fontSize: isSel?12:11, fontWeight:700, fontFamily:"var(--font-mono)",
                boxShadow:"0 4px 12px rgba(0,0,0,0.25)",
                whiteSpace:"nowrap",
                transform: isSel?"scale(1.1)":"scale(1)",
              }}>{fmtPrice(e.price, currency)}</div>
              <div style={{ width:0, height:0, borderLeft:"6px solid transparent", borderRight:"6px solid transparent", borderTop:`8px solid ${isSel?"var(--primary)":"var(--line-strong)"}`, margin:"0 auto" }} />
            </button>
          );
        })}
      </div>

      {/* Top filter overlay */}
      <div style={{ position:"absolute", top: isMobile?14:18, left:14, right:14, display:"flex", gap:8, zIndex:30 }}>
        <div style={{ flex:1, background:"var(--bg)", border:"1px solid var(--line)", borderRadius:"var(--radius)", padding:"10px 14px", display:"flex", alignItems:"center", gap:8, boxShadow:"0 4px 12px rgba(0,0,0,0.15)" }}>
          <I.search cls="ico-sm" />
          <span style={{ fontSize:13, color:"var(--ink-2)" }}>Bandra, Mumbai · 5 km radius</span>
        </div>
        <button style={{ background:"var(--bg)", border:"1px solid var(--line)", borderRadius:"var(--radius)", padding:"10px 14px", boxShadow:"0 4px 12px rgba(0,0,0,0.15)", color:"var(--ink)" }}>
          <I.filter cls="ico-sm" />
        </button>
      </div>

      {/* Bottom event card */}
      <div style={{ position:"absolute", bottom: isMobile?80:18, left:14, right: isMobile?14:336, width: isMobile?"auto":"unset", maxWidth: isMobile?"unset":540, background:"var(--bg)", borderRadius:"var(--radius-lg)", border:"1px solid var(--line)", padding:14, display:"flex", gap:14, boxShadow:"0 8px 32px rgba(0,0,0,0.3)", zIndex:30 }}>
        <img src={ev.image} alt="" style={{ width:80, height:80, borderRadius:"var(--radius-sm)", objectFit:"cover" }} />
        <div style={{ flex:1, minWidth:0 }}>
          <div className="t-eyebrow" style={{ fontSize:9, marginBottom:4 }}>{ev.tag}</div>
          <div style={{ fontSize:14, fontWeight:600, marginBottom:4, display:"-webkit-box", WebkitLineClamp:2, WebkitBoxOrient:"vertical", overflow:"hidden" }}>{ev.title}</div>
          <div className="t-mono" style={{ fontSize:11, color:"var(--ink-3)" }}>{ev.date} · {ev.time}</div>
          <div style={{ fontSize:11, color:"var(--ink-3)", marginTop:2 }}>{ev.venue} · 1.2 km</div>
        </div>
        <button onClick={()=>nav("detail", ev.id)} className="btn btn-primary" style={{ padding:"6px 14px", fontSize:12, alignSelf:"center" }}>View</button>
      </div>

      {/* Side list (desktop only) */}
      {!isMobile && (
        <div style={{ position:"absolute", top:80, right:18, bottom:18, width:300, background:"var(--bg)", borderRadius:"var(--radius-lg)", border:"1px solid var(--line)", overflow:"auto", zIndex:25, boxShadow:"0 8px 32px rgba(0,0,0,0.2)", paddingBottom:120 }}>
          <div style={{ padding:"14px 16px", borderBottom:"1px solid var(--line)", position:"sticky", top:0, background:"var(--bg)", zIndex:1 }}>
            <h3 style={{ fontSize:14, fontWeight:600 }}>14 events nearby</h3>
            <div className="t-mono" style={{ fontSize:10, color:"var(--ink-3)", marginTop:2, textTransform:"uppercase" }}>Sorted by distance</div>
          </div>
          <div style={{ padding:"4px 14px" }}>
            {DATA.events.slice(0,14).map(e => (
              <div key={e.id} onClick={()=>setSelected(e.id)} style={{ cursor:"pointer", padding:"10px 0", borderBottom:"1px solid var(--line)", display:"flex", gap:10, background: selected===e.id?"color-mix(in oklab, var(--primary) 8%, transparent)":"transparent", margin:"0 -14px", paddingLeft:14, paddingRight:14 }}>
                <img src={e.image} alt="" style={{ width:48, height:48, borderRadius:6, objectFit:"cover" }} />
                <div style={{ flex:1, minWidth:0 }}>
                  <div style={{ fontSize:12, fontWeight:600, overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap" }}>{e.title}</div>
                  <div className="t-mono" style={{ fontSize:10, color:"var(--ink-3)" }}>{e.date} · {fmtPrice(e.price, currency)}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
};

// ─── CALENDAR ─────────────────────────────────────────────────────
const CalendarScreen = ({ tweaks, isMobile, nav }) => {
  const currency = tweaks.currency || "INR";
  const days = [
    { date:"14", dow:"Sat", label:"Tomorrow", count: 5 },
    { date:"15", dow:"Sun", label:"This Sunday", count: 4 },
    { date:"19", dow:"Thu", label:"Next Thu", count: 1 },
    { date:"20", dow:"Fri", label:"Next Fri", count: 1 },
    { date:"21", dow:"Sat", label:"Next Sat", count: 2 },
    { date:"22", dow:"Sun", label:"Next Sun", count: 1 },
  ];
  const [selectedDay, setSelectedDay] = useState("14");
  const dayEvents = DATA.events.filter(e => e.date.includes(` ${selectedDay} Jun`) || e.date.includes(`${selectedDay} Jun`));

  const Hour = ({ hour, evs }) => (
    <div style={{ display:"flex", padding:"12px 0", borderTop:"1px dashed var(--line)" }}>
      <div className="t-mono" style={{ width:60, fontSize:11, color:"var(--ink-3)", paddingTop:2 }}>{hour}</div>
      <div style={{ flex:1, display:"flex", flexDirection:"column", gap:8 }}>
        {evs.length === 0 ? (
          <div style={{ height:14 }} />
        ) : evs.map(e => (
          <div key={e.id} onClick={()=>nav("detail", e.id)} style={{ cursor:"pointer", padding:"10px 14px", background:`oklch(0.92 0.05 ${(e.id.charCodeAt(0)*23)%360})`, color:"#000", borderRadius:"var(--radius-sm)", borderLeft:"3px solid var(--primary)", display:"flex", justifyContent:"space-between", alignItems:"center" }}>
            <div>
              <div style={{ fontSize:13, fontWeight:600 }}>{e.title}</div>
              <div className="t-mono" style={{ fontSize:11, opacity:0.7, marginTop:2 }}>{e.time} · {e.venue}</div>
            </div>
            <span className="t-mono" style={{ fontSize:11, fontWeight:600 }}>{fmtPrice(e.price, currency)}</span>
          </div>
        ))}
      </div>
    </div>
  );

  // bucket events by hour
  const hours = ["6 PM","7 PM","8 PM","9 PM","10 PM","11 PM"];
  const bucketed = hours.map(h => ({ h, evs: dayEvents.filter(e=>{
    const evHour = parseInt(e.time);
    const hHour = parseInt(h);
    return evHour === hHour || (Math.abs(evHour-hHour)===0);
  }).slice(0, 2) }));

  return (
    <div style={{ padding: isMobile?"16px 0":"28px 28px", maxWidth:900, margin:"0 auto" }}>
      <div style={{ padding: isMobile?"0 18px 20px":"0 0 24px" }}>
        <div className="t-eyebrow" style={{ marginBottom:8 }}>Your week</div>
        <h1 className="t-display" style={{ fontSize: isMobile?28:38 }}>June 2026</h1>
      </div>

      {/* Day strip */}
      <div style={{ display:"flex", gap:8, padding: isMobile?"0 18px":0, overflowX:"auto", marginBottom:24 }}>
        {days.map(d => {
          const active = selectedDay === d.date;
          return (
            <button key={d.date} onClick={()=>setSelectedDay(d.date)} style={{ flexShrink:0, width:82, padding:"12px 8px", borderRadius:"var(--radius)", background: active?"var(--ink)":"var(--surface)", color: active?"var(--bg)":"var(--ink)", border:`1px solid ${active?"var(--ink)":"var(--line)"}`, display:"flex", flexDirection:"column", alignItems:"center", gap:4 }}>
              <span className="t-mono" style={{ fontSize:10, opacity:0.6, textTransform:"uppercase" }}>{d.dow}</span>
              <span className="t-display" style={{ fontSize:22, lineHeight:1 }}>{d.date}</span>
              <span style={{ fontSize:10, color: active?"var(--bg)":"var(--primary)", fontWeight:600, whiteSpace:"nowrap" }}>{d.count} events</span>
            </button>
          );
        })}
      </div>

      {/* Day timeline */}
      <div style={{ padding: isMobile?"0 18px":0 }}>
        <div className="t-eyebrow" style={{ marginBottom:14 }}>{selectedDay} June · {dayEvents.length} events</div>
        {bucketed.map(b => <Hour key={b.h} hour={b.h} evs={b.evs} />)}
      </div>
      <div style={{ height: isMobile?100:40 }} />
    </div>
  );
};

window.SearchScreen = SearchScreen;
window.MapScreen = MapScreen;
window.CalendarScreen = CalendarScreen;
