/* Event Detail + Booking + Tickets + Profile + AI assistant */

const { useState, useEffect } = React;

// ─── EVENT DETAIL ─────────────────────────────────────────────────
const DetailScreen = ({ tweaks, isMobile, nav, eventId }) => {
  const currency = tweaks.currency || "INR";
  const ev = DATA.events.find(e => e.id === eventId) || DATA.events[0];
  const [saved, setSaved] = useState(false);

  return (
    <div>
      {/* Hero image */}
      <div style={{ position:"relative", aspectRatio: isMobile?"4/5":"21/9", maxHeight: isMobile?"unset":520, overflow:"hidden" }}>
        <img src={ev.image} alt="" style={{ width:"100%", height:"100%", objectFit:"cover" }} />
        <div style={{ position:"absolute", inset:0, background:"linear-gradient(to top, rgba(0,0,0,0.7) 0%, transparent 50%)" }} />
        <button onClick={()=>nav("home")} style={{ position:"absolute", top:14, left:14, width:40, height:40, borderRadius:"50%", background:"rgba(0,0,0,0.5)", backdropFilter:"blur(8px)", color:"#fff", display:"flex", alignItems:"center", justifyContent:"center" }}>←</button>
        <button onClick={()=>setSaved(s=>!s)} style={{ position:"absolute", top:14, right:60, width:40, height:40, borderRadius:"50%", background:"rgba(0,0,0,0.5)", backdropFilter:"blur(8px)", color: saved?"var(--accent)":"#fff", display:"flex", alignItems:"center", justifyContent:"center" }}><I.heart cls="ico-sm" /></button>
        <button style={{ position:"absolute", top:14, right:14, width:40, height:40, borderRadius:"50%", background:"rgba(0,0,0,0.5)", backdropFilter:"blur(8px)", color:"#fff", display:"flex", alignItems:"center", justifyContent:"center" }}><I.share cls="ico-sm" /></button>
        {/* Bottom-overlay header for desktop */}
        {!isMobile && (
          <div style={{ position:"absolute", bottom:0, left:0, right:0, padding:"32px 36px", color:"#fff" }}>
            <div className="t-eyebrow" style={{ color:"var(--accent)", marginBottom:8 }}>{ev.tag}</div>
            <h1 className="t-display" style={{ fontSize:54, color:"#fff", maxWidth:800, lineHeight:1 }}>{ev.title}</h1>
          </div>
        )}
      </div>

      <div style={{ display: isMobile?"block":"grid", gridTemplateColumns: isMobile?"":"1fr 360px", gap: isMobile?0:32, maxWidth:1180, margin:"0 auto", padding: isMobile?"20px 18px 100px":"32px 28px" }}>
        {/* Main column */}
        <div>
          {isMobile && (
            <>
              <div className="t-eyebrow" style={{ marginBottom:8 }}>{ev.tag}</div>
              <h1 className="t-display" style={{ fontSize:28, lineHeight:1.05, marginBottom:14 }}>{ev.title}</h1>
            </>
          )}

          {/* Quick facts */}
          <div style={{ display:"grid", gridTemplateColumns: isMobile?"1fr":"repeat(2,1fr)", gap:12, marginBottom:24 }}>
            {[
              { icon:"calendar", k:"When", v:`${ev.date} · ${ev.time}` },
              { icon:"pin", k:"Venue", v:`${ev.venue}, ${ev.area}` },
              { icon:"ticket", k:"Tickets", v:`From ${fmtPrice(ev.price, currency)}` },
              { icon:"users", k:"Going", v:`${ev.friends} friends · ${300+(ev.id.charCodeAt(0)%500)} others` },
            ].map(f => {
              const Icon = I[f.icon];
              return (
                <div key={f.k} style={{ display:"flex", gap:12, padding:"12px 14px", background:"var(--surface)", border:"1px solid var(--line)", borderRadius:"var(--radius)" }}>
                  <div style={{ width:32, height:32, borderRadius:8, background:"var(--bg)", display:"flex", alignItems:"center", justifyContent:"center", color:"var(--primary)", flexShrink:0 }}><Icon cls="ico-sm" /></div>
                  <div>
                    <div className="t-eyebrow" style={{ fontSize:9, marginBottom:2 }}>{f.k}</div>
                    <div style={{ fontSize:13, fontWeight:500 }}>{f.v}</div>
                  </div>
                </div>
              );
            })}
          </div>

          {/* About */}
          <h2 className="t-display" style={{ fontSize:18, marginBottom:10 }}>About</h2>
          <p style={{ color:"var(--ink-2)", lineHeight:1.6, fontSize:14, marginBottom:24 }}>
            {ev.about || `Join us for an unforgettable evening of ${ev.tag.toLowerCase()} at ${ev.venue}. This is one of the most anticipated events in ${ev.area} this season — expect an electric atmosphere, top performers, and a crowd that knows how to show up.`}
          </p>

          {/* Lineup */}
          {ev.lineup && (
            <>
              <h2 className="t-display" style={{ fontSize:18, marginBottom:10 }}>Lineup</h2>
              <div style={{ display:"flex", gap:10, flexWrap:"wrap", marginBottom:24 }}>
                {ev.lineup.map(p => (
                  <div key={p} style={{ padding:"6px 14px", background:"var(--surface)", border:"1px solid var(--line)", borderRadius:999, fontSize:12, fontWeight:500 }}>{p}</div>
                ))}
              </div>
            </>
          )}

          {/* Friends going */}
          {ev.friends > 0 && (
            <>
              <h2 className="t-display" style={{ fontSize:18, marginBottom:10 }}>Friends going</h2>
              <div className="card" style={{ padding:"14px 16px", marginBottom:24 }}>
                <div style={{ display:"flex", alignItems:"center", gap:14 }}>
                  <div style={{ display:"flex" }}>
                    {DATA.friends.slice(0, ev.friends).map((f,i) => (
                      <div key={f.name} style={{ width:36, height:36, borderRadius:"50%", background:f.color, color:"#fff", marginLeft:i?-12:0, border:"2px solid var(--surface)", display:"flex", alignItems:"center", justifyContent:"center", fontSize:13, fontWeight:700 }}>{f.initial}</div>
                    ))}
                  </div>
                  <div style={{ flex:1 }}>
                    <div style={{ fontSize:13, fontWeight:600 }}>{DATA.friends.slice(0, ev.friends).map(f=>f.name.split(" ")[0]).join(", ")} are going</div>
                    <div style={{ fontSize:11, color:"var(--ink-3)", marginTop:2 }}>Want to make a group plan?</div>
                  </div>
                  <button className="btn btn-ghost" style={{ padding:"6px 12px", fontSize:12 }}><I.users cls="ico-sm" />Group book</button>
                </div>
              </div>
            </>
          )}

          {/* Venue */}
          <h2 className="t-display" style={{ fontSize:18, marginBottom:10 }}>Venue</h2>
          <div className="card" style={{ overflow:"hidden", marginBottom:24 }}>
            <div style={{ height:140, background:"linear-gradient(135deg, var(--surface), var(--surface-2))", position:"relative" }}>
              <svg viewBox="0 0 400 140" style={{ width:"100%", height:"100%", opacity:0.5 }}>
                <path d="M 0 70 Q 100 60, 200 80 T 400 70" stroke="var(--ink-3)" strokeWidth="2" fill="none" />
                <circle cx="200" cy="70" r="8" fill="var(--primary)" />
              </svg>
            </div>
            <div style={{ padding:14 }}>
              <div style={{ fontSize:14, fontWeight:600 }}>{ev.venue}</div>
              <div style={{ fontSize:12, color:"var(--ink-3)", marginTop:4 }}>{ev.area}, {DATA.city} · 2.4 km away</div>
            </div>
          </div>

          {/* Reviews */}
          <h2 className="t-display" style={{ fontSize:18, marginBottom:10 }}>What people say</h2>
          <div style={{ display:"grid", gridTemplateColumns: isMobile?"1fr":"repeat(2,1fr)", gap:12, marginBottom:24 }}>
            {[
              { n:"Priya M.", t:"Best gig of the year. Sound was crystal." },
              { n:"Karan S.", t:"Got there early — totally worth it." },
            ].map(r => (
              <div key={r.n} className="card" style={{ padding:14 }}>
                <div style={{ display:"flex", gap:8, marginBottom:8, color:"var(--accent)" }}>★★★★★</div>
                <p style={{ fontSize:13, color:"var(--ink-2)", lineHeight:1.5, marginBottom:10 }}>"{r.t}"</p>
                <div className="t-mono" style={{ fontSize:11, color:"var(--ink-3)" }}>— {r.n}</div>
              </div>
            ))}
          </div>
        </div>

        {/* Booking sidebar (desktop) */}
        {!isMobile && (
          <aside style={{ position:"sticky", top:90, height:"fit-content" }}>
            <div className="card" style={{ padding:20 }}>
              <div className="t-eyebrow" style={{ marginBottom:8 }}>Tickets</div>
              <div style={{ display:"flex", alignItems:"baseline", gap:8, marginBottom:14 }}>
                <span className="t-display" style={{ fontSize:32 }}>{fmtPrice(ev.price, currency)}</span>
                <span style={{ fontSize:12, color:"var(--ink-3)" }}>onwards</span>
              </div>
              <div style={{ padding:"10px 12px", background:"color-mix(in oklab, var(--accent) 12%, transparent)", borderRadius:"var(--radius-sm)", fontSize:12, color:"var(--accent)", marginBottom:14, display:"flex", alignItems:"center", gap:8 }}>
                <I.bolt cls="ico-sm" /><span style={{ fontWeight:600 }}>Selling fast</span><span style={{ color:"var(--ink-2)" }}>· 18 booked in last hour</span>
              </div>
              <button onClick={()=>nav("booking", ev.id)} className="btn btn-primary" style={{ width:"100%", padding:"12px", fontSize:14, marginBottom:8 }}>Book now</button>
              <button className="btn btn-ghost" style={{ width:"100%", padding:"10px", fontSize:13 }}><I.users cls="ico-sm" />Group book (2+)</button>
              <div style={{ marginTop:16, paddingTop:16, borderTop:"1px solid var(--line)", fontSize:11, color:"var(--ink-3)", lineHeight:1.6 }}>
                Mobile ticket · QR entry · Refundable up to 24h before · Free reschedule
              </div>
            </div>
          </aside>
        )}
      </div>

      {/* Mobile sticky CTA */}
      {isMobile && (
        <div style={{ position:"absolute", bottom:0, left:0, right:0, padding:"12px 18px 18px", background:"var(--bg)", borderTop:"1px solid var(--line)", display:"flex", gap:10, alignItems:"center", zIndex:40 }}>
          <div>
            <div className="t-mono" style={{ fontSize:10, color:"var(--ink-3)" }}>FROM</div>
            <div className="t-display" style={{ fontSize:18 }}>{fmtPrice(ev.price, currency)}</div>
          </div>
          <button onClick={()=>nav("booking", ev.id)} className="btn btn-primary" style={{ flex:1, padding:"12px", fontSize:14 }}>Book now</button>
        </div>
      )}
    </div>
  );
};

// ─── BOOKING (seat select + checkout) ────────────────────────────
const BookingScreen = ({ tweaks, isMobile, nav, eventId }) => {
  const currency = tweaks.currency || "INR";
  const ev = DATA.events.find(e => e.id === eventId) || DATA.events[0];
  const [step, setStep] = useState(0);
  const [tier, setTier] = useState("standard");
  const [qty, setQty] = useState(2);
  const [paid, setPaid] = useState(false);

  const tiers = [
    { id:"early", label:"Early bird", price: ev.price, sold:true, sub:"Sold out" },
    { id:"standard", label:"Standard", price: Math.round(ev.price * 1.2), sub:"42 left" },
    { id:"premium", label:"Premium", price: Math.round(ev.price * 2), sub:"VIP entry, free drink" },
  ];

  const selectedTier = tiers.find(t => t.id === tier);
  const subtotal = selectedTier.price * qty;
  const fees = Math.round(subtotal * 0.06);
  const total = subtotal + fees;

  const Step = ({ n, label, active, done }) => (
    <div style={{ display:"flex", alignItems:"center", gap:8, opacity: done||active?1:0.4, flexShrink:0 }}>
      <div style={{ width:24, height:24, borderRadius:"50%", background: done?"var(--primary)":active?"var(--ink)":"var(--surface)", color: done||active?"var(--ink-on-primary)":"var(--ink)", border: `1px solid ${active||done?"transparent":"var(--line)"}`, display:"flex", alignItems:"center", justifyContent:"center", fontSize:11, fontWeight:700, fontFamily:"var(--font-mono)", flexShrink:0 }}>{done?"✓":n}</div>
      <span style={{ fontSize:12, fontWeight: active?600:500, whiteSpace:"nowrap" }}>{label}</span>
    </div>
  );

  return (
    <div style={{ maxWidth:760, margin:"0 auto", padding: isMobile?"16px 0 100px":"24px 28px 80px" }}>
      <div style={{ padding: isMobile?"0 18px":0 }}>
        <button onClick={()=>nav("detail", eventId)} style={{ fontSize:12, color:"var(--ink-3)", marginBottom:14, whiteSpace:"nowrap" }}>← Back to event</button>
        <div className="t-eyebrow" style={{ marginBottom:6 }}>Booking · {ev.title}</div>
      </div>
      <div style={{ display:"flex", gap: isMobile?10:18, padding: isMobile?"14px 18px":"14px 0", borderBottom:"1px solid var(--line)", marginBottom:24, overflowX:"auto", alignItems:"center" }}>
        <Step n={1} label="Tickets" active={step===0} done={step>0} />
        <span style={{ color:"var(--line-strong)", flexShrink:0 }}>—</span>
        <Step n={2} label="Details" active={step===1} done={step>1} />
        <span style={{ color:"var(--line-strong)", flexShrink:0 }}>—</span>
        <Step n={3} label="Payment" active={step===2} done={paid} />
      </div>

      <div style={{ padding: isMobile?"0 18px":0 }}>
      {step === 0 && (
        <div>
          <h2 className="t-display" style={{ fontSize:22, marginBottom:14 }}>Choose your tier</h2>
          <div style={{ display:"flex", flexDirection:"column", gap:10, marginBottom:24 }}>
            {tiers.map(t => {
              const sel = tier === t.id;
              return (
                <button key={t.id} onClick={()=>!t.sold && setTier(t.id)} disabled={t.sold} style={{
                  textAlign:"left", padding:"16px 18px",
                  background: sel?"color-mix(in oklab, var(--primary) 12%, var(--surface))":"var(--surface)",
                  border:`2px solid ${sel?"var(--primary)":"var(--line)"}`,
                  borderRadius:"var(--radius)",
                  opacity: t.sold?0.5:1,
                  display:"flex", justifyContent:"space-between", alignItems:"center",
                }}>
                  <div>
                    <div style={{ fontSize:14, fontWeight:600 }}>{t.label}</div>
                    <div style={{ fontSize:12, color:"var(--ink-3)", marginTop:4 }}>{t.sub}</div>
                  </div>
                  <div className="t-display" style={{ fontSize:22 }}>{fmtPrice(t.price, currency)}</div>
                </button>
              );
            })}
          </div>

          <h3 className="t-display" style={{ fontSize:16, marginBottom:12 }}>How many?</h3>
          <div style={{ display:"flex", alignItems:"center", gap:14, marginBottom:24 }}>
            <button onClick={()=>setQty(q=>Math.max(1,q-1))} style={{ width:42, height:42, borderRadius:"50%", border:"1px solid var(--line)", color:"var(--ink)", fontSize:20 }}>−</button>
            <div className="t-display" style={{ fontSize:36, minWidth:60, textAlign:"center" }}>{qty}</div>
            <button onClick={()=>setQty(q=>Math.min(8,q+1))} style={{ width:42, height:42, borderRadius:"50%", border:"1px solid var(--line)", color:"var(--ink)", fontSize:20 }}>+</button>
            {qty >= 2 && <span style={{ marginLeft:14, padding:"4px 12px", background:"color-mix(in oklab, var(--accent) 18%, transparent)", color:"var(--accent)", borderRadius:999, fontSize:11, fontWeight:600 }}>Group booking</span>}
          </div>

          <div className="card" style={{ padding:14, marginBottom:24, fontSize:12, color:"var(--ink-2)" }}>
            <div style={{ display:"flex", justifyContent:"space-between", marginBottom:6 }}><span>{qty} × {selectedTier.label}</span><span>{fmtPrice(subtotal, currency)}</span></div>
            <div style={{ display:"flex", justifyContent:"space-between", color:"var(--ink-3)" }}><span>Booking fees</span><span>{fmtPrice(fees, currency)}</span></div>
            <div style={{ display:"flex", justifyContent:"space-between", marginTop:10, paddingTop:10, borderTop:"1px dashed var(--line-strong)", fontSize:14, fontWeight:600, color:"var(--ink)" }}><span>Total</span><span>{fmtPrice(total, currency)}</span></div>
          </div>
        </div>
      )}

      {step === 1 && (
        <div>
          <h2 className="t-display" style={{ fontSize:22, marginBottom:14 }}>Your details</h2>
          {[{l:"Name",v:"Aarav K."},{l:"Email",v:"aarav.k@noesis.io"},{l:"Phone",v:"+91 98XXX 23492"}].map(f => (
            <div key={f.l} style={{ marginBottom:12 }}>
              <div className="t-eyebrow" style={{ marginBottom:6 }}>{f.l}</div>
              <input defaultValue={f.v} style={{ width:"100%", padding:"12px 14px", background:"var(--surface)", border:"1px solid var(--line)", borderRadius:"var(--radius)", color:"var(--ink)", fontSize:14, outline:"none", fontFamily:"inherit" }} />
            </div>
          ))}
          <label style={{ display:"flex", gap:10, marginTop:14, fontSize:13, color:"var(--ink-2)" }}>
            <input type="checkbox" defaultChecked />
            <span>Send me reminders 24h and 1h before event</span>
          </label>
        </div>
      )}

      {step === 2 && !paid && (
        <div>
          <h2 className="t-display" style={{ fontSize:22, marginBottom:14 }}>Payment</h2>
          <div style={{ display:"flex", gap:8, marginBottom:18, flexWrap:"wrap" }}>
            {["UPI","Card","Wallet","Net banking"].map((m,i) => (
              <button key={m} style={{ padding:"10px 16px", borderRadius:"var(--radius)", background: i===0?"var(--ink)":"var(--surface)", color: i===0?"var(--bg)":"var(--ink)", border:`1px solid ${i===0?"var(--ink)":"var(--line)"}`, fontSize:12, fontWeight:600 }}>{m}</button>
            ))}
          </div>
          <div className="card" style={{ padding:18 }}>
            <div className="t-eyebrow" style={{ marginBottom:8 }}>UPI ID</div>
            <input defaultValue="aarav@okhdfcbank" style={{ width:"100%", padding:"12px 14px", background:"var(--bg)", border:"1px solid var(--line)", borderRadius:"var(--radius)", color:"var(--ink)", fontSize:14, outline:"none", fontFamily:"inherit", marginBottom:12 }} />
            <div className="card" style={{ padding:12, marginBottom:0, fontSize:11, color:"var(--ink-3)", display:"flex", justifyContent:"space-between" }}>
              <span>You'll pay</span><span className="t-mono" style={{ color:"var(--ink)", fontWeight:600 }}>{fmtPrice(total, currency)}</span>
            </div>
          </div>
        </div>
      )}

      {step === 2 && paid && (
        <div style={{ textAlign:"center", padding:"40px 20px" }}>
          <div style={{ width:80, height:80, borderRadius:"50%", background:"color-mix(in oklab, #10b981 20%, transparent)", display:"flex", alignItems:"center", justifyContent:"center", margin:"0 auto 20px", color:"#10b981", fontSize:36 }}>✓</div>
          <h2 className="t-display" style={{ fontSize:28, marginBottom:8 }}>You're in.</h2>
          <p style={{ color:"var(--ink-2)", marginBottom:24 }}>{qty} ticket{qty>1?"s":""} for {ev.title}</p>
          <button onClick={()=>nav("tickets")} className="btn btn-primary">View ticket</button>
        </div>
      )}
      </div>

      {/* Footer CTA */}
      {!paid && (
        <div style={{ position: isMobile?"absolute":"sticky", bottom:0, left:0, right:0, padding: isMobile?"14px 18px 18px":"14px 18px", background:"var(--bg)", borderTop:"1px solid var(--line)", display:"flex", justifyContent:"space-between", alignItems:"center", gap:14, zIndex:40 }}>
          <div>
            <div className="t-mono" style={{ fontSize:10, color:"var(--ink-3)" }}>TOTAL</div>
            <div className="t-display" style={{ fontSize:20 }}>{fmtPrice(total, currency)}</div>
          </div>
          <button onClick={()=>{
            if (step < 2) setStep(step+1);
            else setPaid(true);
          }} className="btn btn-primary" style={{ flex:1, padding:"12px", fontSize:14, maxWidth:300 }}>
            {step === 0 ? "Continue" : step === 1 ? "Continue to pay" : "Pay now"} →
          </button>
        </div>
      )}
    </div>
  );
};

window.DetailScreen = DetailScreen;
window.BookingScreen = BookingScreen;
