// Dinner Detail
const { IconMapPin: DnIconMapPin, IconCalendar: DnIconCalendar, IconUsers: DnIconUsers,
        IconLinkedIn: DnIconLinkedIn, IconFolder: DnIconFolder, IconExternal: DnIconExternal,
        IconCheck: DnIconCheck, IconClock: DnIconClock } = window.MAIcons;

function DinnerScreen({ ev, onBack }) {
  const [search, setSearch] = React.useState("");
  const [sourceFilter, setSourceFilter] = React.useState("all");

  const filteredRoster = ev.roster.filter(d => {
    if (sourceFilter !== "all" && d.source !== sourceFilter) return false;
    if (search) {
      const s = search.toLowerCase();
      if (!`${d.name} ${d.company} ${d.title}`.toLowerCase().includes(s)) return false;
    }
    return true;
  });

  return (
    <div className="view-enter view-enter-active page page-wide">
      <Crumb items={[
        { label: "Events", onClick: () => onBack() },
        { label: ev.title },
      ]} />

      {/* Hero — sponsor-forward */}
      <div className="card" style={{padding: 0, marginBottom: 32, overflow:"hidden"}}>
        <div style={{padding:"32px 36px 28px", borderBottom:"1px solid var(--line)"}}>
          <div style={{display:"flex", gap: 14, alignItems:"center", marginBottom: 10}}>
            <span style={{fontSize:11, fontWeight:600, letterSpacing:"0.12em", textTransform:"uppercase", color:"var(--ma-blue-bright)"}}>
              Sponsor dinner
            </span>
            <SeverityPill sev={ev.severity} />
            {ev.blueprintApproved && <Pill kind="blue" dot={false}><DnIconCheck size={11} /> Blueprint approved</Pill>}
          </div>
          <h1 className="serif" style={{fontWeight:500, fontSize: 36, letterSpacing:"-0.022em", margin:"6px 0 16px", lineHeight: 1.1, maxWidth:"22ch"}}>{ev.title}</h1>
          <div style={{display:"flex", gap:32, color:"var(--muted)", fontSize:14, flexWrap:"wrap"}}>
            <span style={{display:"flex", gap:7, alignItems:"center"}}><DnIconCalendar size={14} /><strong style={{color:"var(--ink)", fontWeight:500}}>{window.MAData.fmtDate(ev.start, {weekday:"long", month:"long", day:"numeric", year:"numeric"})}</strong></span>
            <span style={{display:"flex", gap:7, alignItems:"center"}}><DnIconMapPin size={14} /><strong style={{color:"var(--ink)", fontWeight:500}}>{ev.location.venue}</strong> · {ev.location.city}, {ev.location.state || ev.location.country}</span>
            <span style={{display:"flex", gap:7, alignItems:"center"}}><DnIconClock size={14} />6:30 – 9:30 PM local</span>
          </div>
        </div>

        {/* Sponsor strip */}
        <div style={{padding:"28px 36px", background:"var(--surface-tint)", display:"flex", gap:32, alignItems:"center"}}>
          <div style={{
            width: 88, height: 88, borderRadius: 16,
            background: "linear-gradient(135deg, #001a4a, #00429d)",
            display:"grid", placeItems:"center", color:"white",
            fontWeight: 600, fontSize: 14, letterSpacing:"0.04em",
            textAlign:"center", padding: "0 10px"
          }}>
            {ev.sponsor.split(" ").map((w, i, arr) => arr.length > 1 ? w[0] : w.slice(0,3)).join("").toUpperCase()}
          </div>
          <div style={{flex:1}}>
            <div className="eyebrow muted">Hosted by</div>
            <h2 className="section" style={{marginTop: 6, marginBottom: 6}}>{ev.sponsor}</h2>
            <div style={{color:"var(--muted)", fontSize: 13.5, maxWidth:"60ch"}}>
              {ev.sponsorAttendees.length} executive{ev.sponsorAttendees.length===1?"":"s"} attending from {ev.sponsor}. Hosted, single-track format. Up to 15 delegate seats.
            </div>
          </div>
          <div style={{display:"flex", gap:12}}>
            <button className="btn secondary"><DnIconExternal size={14} />Salesforce</button>
            <button className="btn primary">View blueprint</button>
          </div>
        </div>
      </div>

      {/* Metrics */}
      <div style={{display:"grid", gridTemplateColumns:"repeat(4, minmax(0, 1fr))", gap:16, marginBottom: 40}}>
        <MetricCard
          label="Delegates registered"
          value={ev.registered}
          context={`Target ${ev.target} · ${Math.round(ev.registered/ev.target*100)}% filled`}
          footRight={
            <div style={{width:90}}>
              <div className="bar"><span style={{width:`${Math.min(100, ev.registered/ev.target*100)}%`, background: ev.registered/ev.target < 0.7 ? "var(--amber)" : "var(--ma-blue)"}} /></div>
            </div>
          }
        />
        <MetricCard
          label="MA-sourced"
          value={ev.roster.filter(d=>d.source==="MA").length}
          context={`${ev.roster.filter(d=>d.source==="Sponsor").length} sponsor-introduced`}
        />
        <MetricCard
          label="NAW status"
          value={ev.dayOffset > 9 ? `${Math.ceil((ev.nawDate - window.MAData.TODAY)/86400000)}` : "Sent"}
          unit={ev.dayOffset > 9 ? "d" : ""}
          context={ev.dayOffset > 9 ? `Send by ${window.MAData.fmtDate(ev.nawDate)}` : `Distributed ${Math.abs(Math.ceil((ev.nawDate - window.MAData.TODAY)/86400000))} days ago`}
        />
        <MetricCard
          label="Days to dinner"
          value={ev.dayOffset > 0 ? ev.dayOffset : "Past"}
          unit={ev.dayOffset > 0 ? "d" : ""}
          context={ev.dayOffset > 0 ? "Doors open at 6:30 PM" : "Event has concluded"}
        />
      </div>

      <div style={{display:"grid", gridTemplateColumns:"1fr 320px", gap:28, alignItems:"start"}}>
        <div>
          {/* Sponsor attendees */}
          <SectionHead
            eyebrow="Sponsor executives"
            title={`${ev.sponsorAttendees.length} attending from ${ev.sponsor}`}
            lede="Executives representing the sponsor at this dinner."
          />
          <div className="card" style={{padding: 0, marginBottom: 48}}>
            {ev.sponsorAttendees.map((p, i) => (
              <div key={p.id} style={{display:"flex", gap:16, padding:"18px 22px", alignItems:"center", borderBottom: i < ev.sponsorAttendees.length-1 ? "1px solid var(--line)" : "none"}}>
                <div style={{
                  width: 40, height: 40, borderRadius: "50%",
                  background:"var(--ma-blue-50)", color:"var(--ma-blue)",
                  display:"grid", placeItems:"center",
                  fontWeight:600, fontSize:13, letterSpacing:"0.02em"
                }}>
                  {p.name.split(" ").map(n=>n[0]).slice(0,2).join("")}
                </div>
                <div style={{flex:1}}>
                  <div style={{fontWeight:500, fontSize:14.5}}>{p.name}</div>
                  <div style={{color:"var(--muted)", fontSize:13, marginTop:2}}>{p.title} · {p.company}</div>
                </div>
                <button className="icon-btn"><DnIconLinkedIn size={15} /></button>
              </div>
            ))}
          </div>

          {/* Delegate roster */}
          <SectionHead
            eyebrow="Delegate roster"
            title={`${filteredRoster.length} of ${ev.roster.length} delegates`}
            lede="C-suite from invited companies. Each delegate has reviewed the NAW prior to attending."
          />

          <div className="filters" style={{marginBottom: 16, gap:8}}>
            <input className="input" placeholder="Search…" value={search} onChange={e => setSearch(e.target.value)} style={{width: 240}} />
            <FilterChipSm active={sourceFilter==="all"} onClick={()=>setSourceFilter("all")}>All sources</FilterChipSm>
            <FilterChipSm active={sourceFilter==="MA"} onClick={()=>setSourceFilter("MA")}>MA-sourced</FilterChipSm>
            <FilterChipSm active={sourceFilter==="Sponsor"} onClick={()=>setSourceFilter("Sponsor")}>Sponsor-introduced</FilterChipSm>
          </div>

          <div className="card" style={{overflow:"hidden"}}>
            <table className="table">
              <thead>
                <tr>
                  <th>Delegate</th>
                  <th>Company</th>
                  <th>Source</th>
                  <th>Status</th>
                  <th style={{width: 90}}></th>
                </tr>
              </thead>
              <tbody>
                {filteredRoster.map(d => (
                  <tr key={d.id}>
                    <td>
                      <div className="cell-primary">{d.name}</div>
                      <div className="cell-sub">{d.title}</div>
                    </td>
                    <td>{d.company}</td>
                    <td>
                      <span className={`source-chip ${d.source === "MA" ? "ma" : ""}`}>
                        {d.source === "MA" ? "MA-sourced" : d.sponsor}
                      </span>
                    </td>
                    <td>
                      {d.status === "Attending" ? <Pill kind="healthy" dot={false}>Attending</Pill> : <span style={{fontSize:12.5, color:"var(--muted)"}}>{d.status}</span>}
                    </td>
                    <td>
                      <div style={{display:"flex", gap:4, justifyContent:"flex-end"}}>
                        <button className="icon-btn" title="View on LinkedIn"><DnIconLinkedIn size={14} /></button>
                        <button className="icon-btn" title="Open NAW folder" style={{opacity: d.nawFolder ? 1 : 0.3}}><DnIconFolder size={14} /></button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
            {filteredRoster.length === 0 && <EmptyState title="No delegates match this filter" sub="Adjust filters or search term." />}
          </div>
        </div>

        <aside style={{position:"sticky", top:88, display:"flex", flexDirection:"column", gap:20}}>
          <div className="card card-pad">
            <div className="eyebrow muted" style={{marginBottom: 14}}>Event team</div>
            <dl className="dl">
              <dt>Event manager</dt><dd>{ev.manager}</dd>
              <dt>On-site rep</dt><dd>{ev.onsiteRep}</dd>
              <dt>NAW deadline</dt><dd>{window.MAData.fmtDate(ev.nawDate)}</dd>
              <dt>Venue</dt><dd>{ev.location.venue}</dd>
            </dl>
          </div>

          <div className="card card-pad">
            <div className="eyebrow muted" style={{marginBottom: 14}}>Registration</div>
            <div style={{padding:"10px 12px", background:"var(--canvas-2)", borderRadius: 8, fontFamily:"var(--mono)", fontSize:12, color:"var(--ink-2)", wordBreak:"break-all"}}>
              {ev.registrationUrl}
            </div>
            <button className="btn secondary sm" style={{marginTop: 12, width:"100%"}}>Copy registration link</button>
          </div>

          <div className="card card-pad">
            <div className="eyebrow muted" style={{marginBottom: 14}}>Blueprint status</div>
            <div style={{display:"flex", gap:10, alignItems:"center", fontSize:13.5}}>
              {ev.blueprintApproved ? (
                <>
                  <span style={{width:24, height:24, borderRadius:"50%", background:"var(--green-tint)", color:"var(--green)", display:"grid", placeItems:"center"}}><DnIconCheck size={14} /></span>
                  <span>Approved by sponsor</span>
                </>
              ) : (
                <>
                  <span style={{width:24, height:24, borderRadius:"50%", background:"var(--amber-tint)", color:"var(--amber)", display:"grid", placeItems:"center"}}><DnIconClock size={14} /></span>
                  <span>Awaiting sponsor sign-off</span>
                </>
              )}
            </div>
          </div>
        </aside>
      </div>
    </div>
  );
}

function FilterChipSm({ active, onClick, children }) {
  return <button className={`filter-chip ${active?"active":""}`} onClick={onClick} style={{height:30, fontSize:12}}>{children}</button>;
}

window.DinnerScreen = DinnerScreen;
