/* Organiser dashboard + Create event flow */

const { useState } = React;

const OrganiserScreen = ({ tweaks, isMobile, nav }) => {
  const currency = tweaks.currency || "INR";
  const myEvents = [
    { id:"o1", title:"The Daily Standup — Saturday Special", status:"live", date:"14 Jun · 9 PM", venue:"Canvas Laugh Club", sold:182, capacity:240, revenue:91000 },
    { id:"o2", title:"Open Mic Night #47", status:"live", date:"17 Jun · 8 PM", venue:"Antisocial Khar", sold:46, capacity:80, revenue:13800 },
    { id:"o3", title:"Indie Soundcheck — June Edition", status:"draft", date:"22 Jun · 8 PM", venue:"BlueFROG", sold:0, capacity:300, revenue:0 },
    { id:"o4", title:"Standup Showcase #12", status:"past", date:"7 Jun · 9 PM", venue:"Canvas", sold:240, capacity:240, revenue:120000 },
  ];

  const stats = [
    { v:"₹2.24L", l:"Last 30 days", trend:"+24%", up:true },
    { v:"428", l:"Tickets sold", trend:"+18%", up:true },
    { v:"4.8", l:"Avg rating", trend:"+0.2", up:true },
    { v:"73%", l:"Sell-through", trend:"-3%", up:false },
  ];

  // Mini chart
  const Spark = ({ pts, color="var(--primary)" }) => {
    const max = Math.max(...pts), min = Math.min(...pts);
    const w = 100, h = 30;
    const path = pts.map((p,i) => `${i?"L":"M"} ${(i/(pts.length-1))*w} ${h - ((p-min)/(max-min || 1))*h}`).join(" ");
    return <svg viewBox={`0 0 ${w} ${h}`} style={{ width:"100%", height:30 }} preserveAspectRatio="none"><path d={path} stroke={color} strokeWidth="1.5" fill="none" /></svg>;
  };

  const StatusPill = ({ s }) => {
    const cfg = { live: {c:"#10b981", l:"Live"}, draft:{c:"var(--ink-3)", l:"Draft"}, past:{c:"var(--ink-3)", l:"Past"} };
    return <span style={{ padding:"3px 10px", background:`color-mix(in oklab, ${cfg[s].c} 16%, transparent)`, color: cfg[s].c, borderRadius:999, fontSize:10, fontFamily:"var(--font-mono)", fontWeight:700, textTransform:"uppercase", letterSpacing:"0.08em" }}>● {cfg[s].l}</span>;
  };

  return (
    <div style={{ padding: isMobile?"0 0 100px":"28px", maxWidth:1180, margin:"0 auto" }}>
      <div style={{ padding: isMobile?"24px 18px 0":"0 0 20px", display:"flex", justifyContent:"space-between", alignItems:"flex-start", gap:12 }}>
        <div style={{ flex:1, minWidth:0 }}>
          <div className="t-eyebrow" style={{ marginBottom:6 }}>● Organiser dashboard</div>
          <h1 className="t-display" style={{ fontSize: isMobile?24:40, lineHeight:1.1, marginBottom:6 }}>Eclipse Live Co.</h1>
          <div style={{ fontSize:13, color:"var(--ink-3)" }}>4 events · 2 selling · Mumbai</div>
        </div>
        <button onClick={()=>nav("create")} className="btn btn-primary" style={{ padding:"10px 16px", fontSize:13, flexShrink:0, whiteSpace:"nowrap" }}>+ New event</button>
      </div>

      {/* Stats */}
      <div style={{ padding: isMobile?"20px 18px 0":"20px 0 0", display:"grid", gridTemplateColumns: isMobile?"repeat(2,1fr)":"repeat(4,1fr)", gap:12 }}>
        {stats.map(s => (
          <div key={s.l} className="card" style={{ padding:"16px 18px" }}>
            <div className="t-eyebrow" style={{ marginBottom:8 }}>{s.l}</div>
            <div style={{ display:"flex", justifyContent:"space-between", alignItems:"flex-end" }}>
              <div className="t-display" style={{ fontSize:24 }}>{s.v}</div>
              <div className="t-mono" style={{ fontSize:11, color: s.up?"#10b981":"#ef4444", fontWeight:600 }}>{s.up?"↑":"↓"} {s.trend}</div>
            </div>
            <div style={{ marginTop:10 }}>
              <Spark pts={Array.from({length:14}, (_,i)=>Math.sin(i*0.7)*10 + i*2 + Math.random()*8)} color={s.up?"#10b981":"#ef4444"} />
            </div>
          </div>
        ))}
      </div>

      {/* Events table */}
      <div style={{ padding: isMobile?"24px 18px 0":"32px 0 0" }}>
        <h2 className="t-display" style={{ fontSize:18, marginBottom:14 }}>Your events</h2>
        <div className="card" style={{ overflow:"hidden" }}>
          {myEvents.map((e, i) => {
            const pct = (e.sold / e.capacity) * 100;
            return (
              <div key={e.id} style={{ padding:"16px 18px", borderBottom: i<myEvents.length-1?"1px solid var(--line)":"none", display:"grid", gridTemplateColumns: isMobile?"1fr":"1.6fr 1fr 1fr 1fr 80px", gap:14, alignItems:"center" }}>
                <div>
                  <div style={{ display:"flex", alignItems:"center", gap:8, marginBottom:5 }}>
                    <StatusPill s={e.status} />
                  </div>
                  <div style={{ fontSize:14, fontWeight:600 }}>{e.title}</div>
                  <div className="t-mono" style={{ fontSize:11, color:"var(--ink-3)", marginTop:3 }}>{e.date} · {e.venue}</div>
                </div>
                {!isMobile && (
                  <>
                    <div>
                      <div className="t-eyebrow" style={{ marginBottom:4 }}>Sold</div>
                      <div className="t-mono" style={{ fontSize:13, fontWeight:600 }}>{e.sold} / {e.capacity}</div>
                      <div style={{ height:4, background:"var(--surface-2)", borderRadius:2, marginTop:6, overflow:"hidden" }}>
                        <div style={{ width:`${pct}%`, height:"100%", background: pct>80?"#10b981":pct>50?"var(--primary)":"var(--accent)" }} />
                      </div>
                    </div>
                    <div>
                      <div className="t-eyebrow" style={{ marginBottom:4 }}>Revenue</div>
                      <div className="t-display" style={{ fontSize:18 }}>{fmtPrice(e.revenue, currency)}</div>
                    </div>
                    <div>
                      <div className="t-eyebrow" style={{ marginBottom:4 }}>7-day trend</div>
                      <Spark pts={Array.from({length:10}, (_,j)=>Math.sin(j*0.5)*5 + j + Math.random()*3)} />
                    </div>
                    <button className="btn btn-ghost" style={{ padding:"6px 12px", fontSize:11 }}>Manage</button>
                  </>
                )}
                {isMobile && (
                  <div style={{ display:"flex", justifyContent:"space-between", marginTop:6, alignItems:"center" }}>
                    <div className="t-mono" style={{ fontSize:12 }}>{e.sold}/{e.capacity} · {fmtPrice(e.revenue, currency)}</div>
                    <button className="btn btn-ghost" style={{ padding:"5px 10px", fontSize:11 }}>Manage</button>
                  </div>
                )}
              </div>
            );
          })}
        </div>
      </div>

      {/* Insights */}
      <div style={{ padding: isMobile?"24px 18px 0":"32px 0 0", display:"grid", gridTemplateColumns: isMobile?"1fr":"1fr 1fr", gap:14 }}>
        <div className="card" style={{ padding:18 }}>
          <h3 className="t-display" style={{ fontSize:16, marginBottom:14 }}>Audience</h3>
          <div style={{ display:"flex", flexDirection:"column", gap:10 }}>
            {[
              { l:"Bandra & Khar", v:34 },
              { l:"South Mumbai", v:26 },
              { l:"Andheri W", v:18 },
              { l:"Powai", v:12 },
              { l:"Other", v:10 },
            ].map(b => (
              <div key={b.l}>
                <div style={{ display:"flex", justifyContent:"space-between", fontSize:12, marginBottom:5 }}>
                  <span>{b.l}</span><span className="t-mono" style={{ fontWeight:600 }}>{b.v}%</span>
                </div>
                <div style={{ height:6, background:"var(--surface-2)", borderRadius:3, overflow:"hidden" }}>
                  <div style={{ width:`${b.v*2.5}%`, height:"100%", background:"var(--primary)" }} />
                </div>
              </div>
            ))}
          </div>
        </div>
        <div className="card" style={{ padding:18 }}>
          <h3 className="t-display" style={{ fontSize:16, marginBottom:14 }}>Recent reviews</h3>
          {[
            { n:"Riya K.", r:5, t:"Vibe was unreal, sound was crisp, will be back." },
            { n:"Sahil M.", r:5, t:"Best comedy night I've been to in months." },
            { n:"Tanya P.", r:4, t:"Great show, but parking was a nightmare." },
          ].map(r => (
            <div key={r.n} style={{ padding:"10px 0", borderTop:"1px solid var(--line)" }}>
              <div style={{ display:"flex", justifyContent:"space-between", marginBottom:4 }}>
                <span className="t-mono" style={{ fontSize:11, fontWeight:600 }}>{r.n}</span>
                <span style={{ color:"var(--accent)", fontSize:11 }}>{"★".repeat(r.r)}</span>
              </div>
              <p style={{ fontSize:12, color:"var(--ink-2)", lineHeight:1.5 }}>"{r.t}"</p>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

// ─── CREATE EVENT (multi-step) ────────────────────────────────
const CreateEventScreen = ({ tweaks, isMobile, nav }) => {
  const [step, setStep] = useState(0);
  const steps = ["Basics", "Venue & Date", "Tickets", "Publish"];
  const [data, setData] = useState({
    title: "Indie Soundcheck — June Edition",
    cat: "Music",
    venue: "BlueFROG, Lower Parel",
    date: "22 Jun 2026",
    time: "8 PM",
    capacity: 300,
    tiers: [{ name:"Early bird", price:799, qty:80 }, { name:"Standard", price:1199, qty:200 }],
  });

  const Field = ({ l, children }) => (
    <div style={{ marginBottom:14 }}>
      <div className="t-eyebrow" style={{ marginBottom:6 }}>{l}</div>
      {children}
    </div>
  );
  const inputCss = { 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" };

  return (
    <div style={{ maxWidth:920, margin:"0 auto", padding: isMobile?"16px 0 100px":"28px 28px 80px" }}>
      <div style={{ padding: isMobile?"0 18px":0 }}>
        <button onClick={()=>nav("organiser")} style={{ fontSize:12, color:"var(--ink-3)", marginBottom:10, whiteSpace:"nowrap" }}>← Back to dashboard</button>
        <h1 className="t-display" style={{ fontSize: isMobile?26:36, marginBottom:20 }}>Create event</h1>
      </div>

      {/* Steps */}
      <div style={{ padding: isMobile?"0 18px":0, display:"flex", gap:6, marginBottom:24, overflowX:"auto" }}>
        {steps.map((s, i) => {
          const active = step === i, done = step > i;
          return (
            <button key={s} onClick={()=>setStep(i)} style={{ flex: isMobile?"0 0 auto":1, padding:"10px 12px", background: active?"var(--ink)":done?"var(--surface)":"transparent", color: active?"var(--bg)":done?"var(--ink)":"var(--ink-3)", border:`1px solid ${active?"var(--ink)":done?"var(--line)":"var(--line)"}`, borderRadius:"var(--radius-sm)", display:"flex", alignItems:"center", gap:8, fontSize:12, fontWeight:600 }}>
              <span className="t-mono" style={{ opacity:0.7 }}>{i+1}</span>
              <span>{s}</span>
              {done && <span style={{ marginLeft:"auto", color:"#10b981" }}>✓</span>}
            </button>
          );
        })}
      </div>

      <div style={{ padding: isMobile?"0 18px":0, display: isMobile?"block":"grid", gridTemplateColumns: isMobile?"":"1fr 320px", gap:28 }}>
        {/* Form */}
        <div>
          {step === 0 && (
            <div className="card" style={{ padding:"20px 22px" }}>
              <Field l="Event title"><input value={data.title} onChange={e=>setData(d=>({...d, title:e.target.value}))} style={inputCss} /></Field>
              <Field l="Category">
                <div style={{ display:"flex", flexWrap:"wrap", gap:8 }}>
                  {DATA.categories.map(c => (
                    <button key={c.id} onClick={()=>setData(d=>({...d, cat:c.label}))} style={{ padding:"8px 14px", borderRadius:999, background: data.cat===c.label?"var(--primary)":"var(--bg)", color: data.cat===c.label?"var(--ink-on-primary)":"var(--ink-2)", border:`1px solid ${data.cat===c.label?"var(--primary)":"var(--line)"}`, fontSize:12, fontWeight: data.cat===c.label?600:500 }}>{c.label}</button>
                  ))}
                </div>
              </Field>
              <Field l="Description"><textarea defaultValue="An intimate showcase of three of Mumbai's most exciting indie acts. Doors at 7 PM, music at 8." rows={4} style={{...inputCss, resize:"vertical", fontFamily:"inherit"}} /></Field>
              <Field l="Cover image">
                <div style={{ height:140, background:"var(--surface-2)", border:"2px dashed var(--line-strong)", borderRadius:"var(--radius)", display:"flex", flexDirection:"column", alignItems:"center", justifyContent:"center", color:"var(--ink-3)", fontSize:13, gap:6 }}>
                  <I.image cls="ico-lg" />
                  <span>Drag image or click to upload</span>
                  <span className="t-mono" style={{ fontSize:10 }}>1920 × 1080 recommended</span>
                </div>
              </Field>
            </div>
          )}

          {step === 1 && (
            <div className="card" style={{ padding:"20px 22px" }}>
              <Field l="Venue"><input value={data.venue} onChange={e=>setData(d=>({...d, venue:e.target.value}))} style={inputCss} /></Field>
              <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:12 }}>
                <Field l="Date"><input value={data.date} onChange={e=>setData(d=>({...d, date:e.target.value}))} style={inputCss} /></Field>
                <Field l="Doors"><input value={data.time} onChange={e=>setData(d=>({...d, time:e.target.value}))} style={inputCss} /></Field>
              </div>
              <Field l="Capacity"><input type="number" value={data.capacity} onChange={e=>setData(d=>({...d, capacity:+e.target.value}))} style={inputCss} /></Field>
              <Field l="Address & directions"><textarea defaultValue="BlueFROG, D/2 Mathuradas Mills, Lower Parel, Mumbai 400013" rows={2} style={{...inputCss, fontFamily:"inherit", resize:"vertical"}} /></Field>
            </div>
          )}

          {step === 2 && (
            <div className="card" style={{ padding:"20px 22px" }}>
              <h3 className="t-display" style={{ fontSize:16, marginBottom:14 }}>Pricing tiers</h3>
              {data.tiers.map((t, i) => (
                <div key={i} style={{ display:"grid", gridTemplateColumns:"2fr 1fr 1fr 32px", gap:8, alignItems:"center", marginBottom:10 }}>
                  <input value={t.name} style={inputCss} onChange={e=>{const ts=[...data.tiers];ts[i].name=e.target.value;setData(d=>({...d,tiers:ts}))}} />
                  <input type="number" value={t.price} style={inputCss} onChange={e=>{const ts=[...data.tiers];ts[i].price=+e.target.value;setData(d=>({...d,tiers:ts}))}} />
                  <input type="number" value={t.qty} style={inputCss} onChange={e=>{const ts=[...data.tiers];ts[i].qty=+e.target.value;setData(d=>({...d,tiers:ts}))}} />
                  <button onClick={()=>setData(d=>({...d, tiers: d.tiers.filter((_,j)=>j!==i)}))} style={{ color:"var(--ink-3)" }}>×</button>
                </div>
              ))}
              <button onClick={()=>setData(d=>({...d, tiers:[...d.tiers, { name:"VIP", price:2499, qty:20 }]}))} className="btn btn-ghost" style={{ marginTop:6, padding:"8px 14px", fontSize:12 }}>+ Add tier</button>
              <div style={{ marginTop:18, paddingTop:18, borderTop:"1px solid var(--line)", fontSize:12, color:"var(--ink-2)", display:"flex", justifyContent:"space-between" }}>
                <span>Estimated revenue at full sell-out</span>
                <span className="t-display" style={{ fontSize:18 }}>{fmtPrice(data.tiers.reduce((s,t)=>s+t.price*t.qty,0), tweaks.currency || "INR")}</span>
              </div>
            </div>
          )}

          {step === 3 && (
            <div className="card" style={{ padding:"20px 22px" }}>
              <div style={{ marginBottom:14, padding:"12px 14px", background:"color-mix(in oklab, #10b981 12%, transparent)", border:"1px solid color-mix(in oklab, #10b981 30%, transparent)", borderRadius:"var(--radius)", fontSize:12, color:"#10b981" }}>
                ✓ Looks good — ready to publish
              </div>
              <h3 className="t-display" style={{ fontSize:18, marginBottom:14 }}>{data.title}</h3>
              <div style={{ display:"grid", gridTemplateColumns:"repeat(2,1fr)", gap:12, fontSize:12 }}>
                {[
                  { l:"Category", v:data.cat },
                  { l:"Venue", v:data.venue },
                  { l:"Date", v:`${data.date} · ${data.time}` },
                  { l:"Capacity", v:`${data.capacity} (${data.tiers.reduce((s,t)=>s+t.qty,0)} sellable)` },
                  { l:"Tiers", v: data.tiers.map(t=>`${t.name} ₹${t.price}`).join(" · ") },
                  { l:"Status", v:"Will be live immediately" },
                ].map(f => (
                  <div key={f.l}>
                    <div className="t-eyebrow" style={{ marginBottom:4 }}>{f.l}</div>
                    <div style={{ fontWeight:500 }}>{f.v}</div>
                  </div>
                ))}
              </div>
              <button onClick={()=>nav("organiser")} className="btn btn-primary" style={{ width:"100%", marginTop:20, padding:"12px", fontSize:14 }}>Publish event →</button>
            </div>
          )}

          {/* Nav buttons */}
          {step < 3 && (
            <div style={{ display:"flex", justifyContent:"space-between", marginTop:18 }}>
              <button onClick={()=>setStep(s=>Math.max(0,s-1))} className="btn btn-ghost" style={{ padding:"10px 16px", fontSize:13, opacity: step===0?0.4:1 }} disabled={step===0}>← Back</button>
              <button onClick={()=>setStep(s=>s+1)} className="btn btn-primary" style={{ padding:"10px 18px", fontSize:13 }}>Continue →</button>
            </div>
          )}
        </div>

        {/* Live preview */}
        {!isMobile && (
          <aside>
            <div className="t-eyebrow" style={{ marginBottom:10 }}>Live preview</div>
            <div className="card" style={{ overflow:"hidden" }}>
              <div style={{ aspectRatio:"5/4", background:"linear-gradient(135deg, var(--surface), var(--surface-2))", display:"flex", alignItems:"center", justifyContent:"center", color:"var(--ink-3)" }}>
                <I.image cls="ico-lg" />
              </div>
              <div style={{ padding:14 }}>
                <div className="t-eyebrow" style={{ marginBottom:6 }}>{data.cat}</div>
                <div style={{ fontSize:14, fontWeight:600, marginBottom:8, lineHeight:1.3 }}>{data.title}</div>
                <div style={{ fontSize:11, color:"var(--ink-2)" }}>
                  <div className="t-mono">{data.date} · {data.time}</div>
                  <div style={{ marginTop:2 }}>{data.venue}</div>
                </div>
                <div style={{ marginTop:10, paddingTop:10, borderTop:"1px solid var(--line)", display:"flex", justifyContent:"space-between" }}>
                  <span className="t-mono" style={{ fontWeight:600 }}>from ₹{Math.min(...data.tiers.map(t=>t.price))}</span>
                  <span style={{ background:"var(--primary)", color:"var(--ink-on-primary)", padding:"4px 12px", borderRadius:999, fontSize:11, fontWeight:600 }}>Book</span>
                </div>
              </div>
            </div>
          </aside>
        )}
      </div>
    </div>
  );
};

window.OrganiserScreen = OrganiserScreen;
window.CreateEventScreen = CreateEventScreen;
