/* global React, Icon, Button, Chip, Pill, Panel, ScreenHeader, SectionLabel, AgentNote, TONES, EVENTS, EV_CATEGORIES, EV_STATUS_META, EV_PIPELINE, EV_TRACKED */
const { useState: useEv } = React;

// OfferRoom Events. Discover + track + deep-link register.
// Cards encode two separate axes: source AUTHORITY (first_party / aggregator / inferred)
// and relevance. Only inferred data carries a "verify on source" chip.

function ScrEvents({ tier = "premium", onWayIn }) {
  const [view, setView] = useEv("discover");        // discover | tracked
  const [mode, setMode] = useEv("all");             // all | online | offline
  const [freeOnly, setFreeOnly] = useEv(false);
  const [cat, setCat] = useEv("all");
  const [detail, setDetail] = useEv(null);          // event object or null

  const match = (e) =>
    (mode === "all" || e.mode === mode) &&
    (!freeOnly || e.cost.free) &&
    (cat === "all" || e.category === cat);

  const companyEvents = EVENTS.filter(e => e.group === "company" && match(e));
  const profileEvents = EVENTS.filter(e => e.group === "profile" && match(e));
  const trackedCount = EV_TRACKED.length;
  const locked = tier === "free";

  return (
    <div style={{ maxWidth: 1140, margin: "0 auto", padding: "8px 0 40px" }}>
      <ScreenHeader
        eyebrow="Get introduced"
        title="Events"
        lede="Info sessions, career fairs, and meetups matched to your shortlisted companies and your profile. Save the good ones, register on the event's own page, and we handle the calendar and the follow-up."
        actions={<Button variant="secondary" size="sm" icon="refresh">Searched 3h ago</Button>}
      />

      {/* View switch + filter bar */}
      <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 18, flexWrap: "wrap" }}>
        <div style={{ display: "inline-flex", background: "var(--paper-sunken)", border: "1px solid var(--ink-100)", borderRadius: 8, padding: 3, gap: 2, marginRight: 6 }}>
          {[{ k: "discover", l: "Discover" }, { k: "tracked", l: `Tracked · ${trackedCount}` }].map(o => (
            <button key={o.k} onClick={() => setView(o.k)} style={{
              padding: "6px 14px", borderRadius: 6, fontSize: 12.5, fontWeight: 500, fontFamily: "var(--font-sans)", cursor: "pointer", border: "none",
              background: view === o.k ? "#fff" : "transparent", color: view === o.k ? "var(--fg-0)" : "var(--fg-2)",
              boxShadow: view === o.k ? "0 1px 2px rgba(31,27,22,0.08)" : "none",
            }}>{o.l}</button>
          ))}
        </div>
        {view === "discover" && <>
          <EvFilterChip active={mode === "all"} onClick={() => setMode("all")} icon="target">Everywhere</EvFilterChip>
          <EvFilterChip active={mode === "offline"} onClick={() => setMode(mode === "offline" ? "all" : "offline")} icon="pin">In person · US</EvFilterChip>
          <EvFilterChip active={mode === "online"} onClick={() => setMode(mode === "online" ? "all" : "online")} icon="globe">Online</EvFilterChip>
          <span style={{ width: 1, height: 20, background: "var(--ink-100)", margin: "0 4px" }}/>
          <EvFilterChip active={freeOnly} onClick={() => setFreeOnly(f => !f)} icon="check">Free only</EvFilterChip>
          <select value={cat} onChange={e => setCat(e.target.value)} style={{
            padding: "6px 10px", borderRadius: 999, fontSize: 12.5, fontFamily: "var(--font-sans)", color: "var(--fg-1)",
            background: "#fff", border: "1px solid var(--ink-100)", cursor: "pointer",
          }}>
            {EV_CATEGORIES.map(c => <option key={c.key} value={c.key}>{c.label}</option>)}
          </select>
          <span style={{ flex: 1 }}/>
          <span style={{ fontSize: 12, color: "var(--fg-2)" }}>{companyEvents.length + profileEvents.length} events</span>
        </>}
      </div>

      {view === "discover" ? (
        <>
          <SectionLabel style={{ marginBottom: 10 }}>For your target companies</SectionLabel>
          {companyEvents.length === 0 ? (
            <EvEmpty note="No company events match these filters. We keep watching your shortlisted companies' event pages and will flag the next one."/>
          ) : (
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginBottom: 26 }}>
              {companyEvents.map(e => <EventCard key={e.id} e={e} onOpen={() => setDetail(e)}/>)}
            </div>
          )}

          <div style={{ display: "flex", alignItems: "baseline", gap: 10, marginBottom: 10 }}>
            <SectionLabel>For your profile</SectionLabel>
            <span style={{ fontSize: 12, color: "var(--fg-3)" }}>Senior PM · fintech · United States</span>
          </div>
          {locked ? (
            <EvLocked count={profileEvents.length}/>
          ) : profileEvents.length === 0 ? (
            <EvEmpty note="Nothing matches these filters right now. Online events widen the pool; try clearing the in-person filter."/>
          ) : (
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
              {profileEvents.map(e => <EventCard key={e.id} e={e} onOpen={() => setDetail(e)}/>)}
            </div>
          )}
        </>
      ) : (
        <EvTracked onOpen={(id) => { const e = EVENTS.find(x => x.id === id); if (e) setDetail(e); }}/>
      )}

      {detail && <EventDetail e={detail} onClose={() => setDetail(null)} onWayIn={onWayIn}/>}
    </div>
  );
}

const EvFilterChip = ({ active, onClick, icon, children }) => (
  <button onClick={onClick} style={{
    display: "inline-flex", alignItems: "center", gap: 6, padding: "6px 12px", borderRadius: 999, cursor: "pointer",
    fontSize: 12.5, fontWeight: 500, fontFamily: "var(--font-sans)",
    background: active ? "#8C1515" : "#fff", color: active ? "#fff" : "var(--fg-1)",
    border: active ? "1px solid transparent" : "1px solid var(--ink-100)", transition: "all 120ms",
  }}>
    <Icon name={icon} size={13}/>{children}
  </button>
);

// Source authority, two axes: authority (how definitive) vs the verify affordance
// (only inferred data). First-party company pages read as definitive.
const SourceChip = ({ source }) => {
  if (source.authority === "inferred") return (
    <span title={`Read from ${source.provider}. Confirm details on ${source.verifyUrl} before you commit.`} style={{
      display: "inline-flex", alignItems: "center", gap: 5, padding: "3px 9px", borderRadius: 999,
      fontSize: 11.5, fontWeight: 600, background: "var(--ochre-tint)", color: "var(--ochre-text)", cursor: "help",
    }}>
      <Icon name="eye" size={12}/>Verify on {source.verifyUrl}
    </span>
  );
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 11.5, color: "var(--fg-3)" }}>
      <Icon name={source.authority === "first_party" ? "check" : "layers"} size={12}/>
      {source.authority === "first_party" ? `From ${source.provider}` : `Via ${source.provider}`}
    </span>
  );
};

const EventCard = ({ e, onOpen }) => {
  const st = e.status && EV_STATUS_META[e.status];
  return (
    <Panel pad={16} style={{ display: "flex", flexDirection: "column", gap: 0, opacity: e.closed ? 0.55 : 1, cursor: "pointer" }} className="cad-ev-card">
      <div onClick={onOpen} style={{ display: "flex", flexDirection: "column", gap: 0 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 8, flexWrap: "wrap" }}>
          <Pill tone={e.mode === "online" ? "slate" : "neutral"}>
            <Icon name={e.mode === "online" ? "globe" : "pin"} size={11}/>{e.mode === "online" ? "Online" : "In person"}
          </Pill>
          <Pill tone="neutral">{e.categoryLabel}</Pill>
          <span style={{ flex: 1 }}/>
          {e.closed
            ? <Pill tone="neutral">Registration closed</Pill>
            : st && <Chip tone={st.tone}>{st.label}</Chip>}
        </div>
        <div style={{ fontFamily: "var(--font-display)", fontSize: 17, fontWeight: 500, letterSpacing: "-0.005em" }}>{e.title}</div>
        <div style={{ fontSize: 13, color: "var(--fg-2)", marginTop: 3 }}>{e.when} · {e.venue}</div>
        {e.tz && <div style={{ fontSize: 12, color: "var(--fg-3)", marginTop: 2, display: "flex", alignItems: "center", gap: 4 }}><Icon name="clock" size={12}/>{e.tz}</div>}

        {/* Why this event (case C) */}
        <div style={{ display: "flex", alignItems: "center", gap: 6, marginTop: 10, fontSize: 12.5, color: e.relevance.company ? "var(--cardinal-700)" : "var(--fg-1)" }}>
          <Icon name="target" size={13}/>
          <span>{e.relevance.company ? <><b>{e.relevance.company}</b> · {e.relevance.reason}</> : e.relevance.reason}</span>
        </div>

        {/* Networking tie-in (case D) */}
        {(e.networking.insiders || e.networking.known > 0) && (
          <div style={{ display: "flex", flexDirection: "column", gap: 3, marginTop: 7 }}>
            {e.networking.insiders && (
              <span style={{ fontSize: 12, color: "var(--sage-text)", display: "inline-flex", alignItems: "center", gap: 5 }}>
                <Icon name="handshake" size={12}/>{e.networking.insiders}
              </span>
            )}
            {e.networking.known > 0 && (
              <span style={{ fontSize: 12, color: "var(--fg-2)", display: "inline-flex", alignItems: "center", gap: 5 }}>
                <Icon name="contacts" size={12}/>{e.networking.knownNote}
              </span>
            )}
          </div>
        )}
      </div>

      <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 12, paddingTop: 12, borderTop: "1px solid var(--ink-50)" }}>
        <span style={{ fontSize: 12.5, fontFamily: "var(--font-mono)", fontWeight: 500, color: e.cost.free ? "var(--sage-text)" : "var(--fg-1)" }}>
          {e.cost.free ? "Free" : e.cost.price}
        </span>
        {e.registerBy && !e.closed && <span style={{ fontSize: 11.5, color: "var(--fg-3)" }}>· {e.registerBy}</span>}
        <span style={{ flex: 1 }}/>
        <SourceChip source={e.source}/>
        <Button variant="ghost" size="sm" icon="chevron" onClick={onOpen} style={{ padding: "5px 8px" }}></Button>
      </div>
    </Panel>
  );
};

// ---- Event detail (slide-over) ----
const EventDetail = ({ e, onClose, onWayIn }) => (
  <div onClick={onClose} style={{ position: "fixed", inset: 0, zIndex: 70, background: "rgba(31,27,22,0.32)", display: "flex", justifyContent: "flex-end" }}>
    <div onClick={ev => ev.stopPropagation()} className="cad-fade" style={{ width: 460, maxWidth: "92vw", height: "100%", background: "var(--paper)", boxShadow: "-12px 0 40px rgba(31,27,22,0.18)", display: "flex", flexDirection: "column", overflow: "hidden" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "16px 20px", borderBottom: "1px solid var(--ink-100)" }}>
        <SectionLabel>Event</SectionLabel>
        <span style={{ flex: 1 }}/>
        <button onClick={onClose} style={{ background: "transparent", border: "none", cursor: "pointer", color: "var(--fg-2)", padding: 4 }}><Icon name="close" size={16}/></button>
      </div>
      <div style={{ flex: 1, overflowY: "auto", padding: "20px 20px 28px", display: "flex", flexDirection: "column", gap: 16 }}>
        <div>
          <div style={{ display: "flex", gap: 6, marginBottom: 10, flexWrap: "wrap" }}>
            <Pill tone={e.mode === "online" ? "slate" : "neutral"}>{e.mode === "online" ? "Online" : "In person"}</Pill>
            <Pill tone="neutral">{e.categoryLabel}</Pill>
            {!e.cost.free && <Pill tone="ochre">Paid · {e.cost.price}</Pill>}
          </div>
          <div style={{ fontFamily: "var(--font-display)", fontSize: 22, fontWeight: 500, letterSpacing: "-0.01em", lineHeight: 1.25 }}>{e.title}</div>
        </div>

        <div style={{ display: "flex", flexDirection: "column", gap: 7, fontSize: 13, color: "var(--fg-1)" }}>
          <span style={{ display: "flex", alignItems: "center", gap: 8 }}><Icon name="calendar" size={14}/>{e.when} · {e.duration}</span>
          {e.tz && <span style={{ display: "flex", alignItems: "center", gap: 8, color: "var(--fg-2)" }}><Icon name="clock" size={14}/>{e.tz}</span>}
          <span style={{ display: "flex", alignItems: "center", gap: 8 }}><Icon name={e.mode === "online" ? "globe" : "pin"} size={14}/>{e.venue}</span>
          <span style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <Icon name="zap" size={14}/>
            <span style={{ fontFamily: "var(--font-mono)", fontWeight: 500, color: e.cost.free ? "var(--sage-text)" : "var(--fg-0)" }}>{e.cost.free ? "Free" : e.cost.price}</span>
            {e.registerBy && <span style={{ color: "var(--fg-3)" }}>· {e.registerBy}</span>}
          </span>
        </div>

        <p style={{ fontSize: 13.5, lineHeight: 1.55, color: "var(--fg-1)", margin: 0 }}>{e.detail}</p>

        <div>
          <SectionLabel style={{ marginBottom: 8 }}>Why you're seeing this</SectionLabel>
          <div style={{ fontSize: 13, color: "var(--fg-1)", display: "flex", alignItems: "flex-start", gap: 8, padding: "10px 12px", borderRadius: 8, background: "rgba(140,21,21,0.04)", border: "1px solid rgba(140,21,21,0.10)" }}>
            <Icon name="target" size={14} style={{ marginTop: 1, flexShrink: 0 }}/>
            <span>
              {e.relevance.company ? <><b>{e.relevance.company}</b> · {e.relevance.reason}.</> : <>{e.relevance.reason}.</>}
              {e.relevance.job && <> Linked to <b>{e.relevance.job}</b> on your tracker.</>}
            </span>
          </div>
        </div>

        {(e.networking.insiders || e.networking.known > 0) && (
          <div>
            <SectionLabel style={{ marginBottom: 8 }}>Who you could meet</SectionLabel>
            <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
              {e.networking.insiders && (
                <span style={{ fontSize: 13, color: "var(--sage-text)", display: "flex", alignItems: "center", gap: 8 }}><Icon name="handshake" size={14}/>{e.networking.insiders}</span>
              )}
              {e.networking.known > 0 && (
                <span style={{ fontSize: 13, color: "var(--fg-1)", display: "flex", alignItems: "center", gap: 8 }}><Icon name="contacts" size={14}/>{e.networking.knownNote}</span>
              )}
              <button onClick={() => onWayIn && onWayIn(e.relevance.company)} style={{ alignSelf: "flex-start", marginTop: 2, display: "inline-flex", alignItems: "center", gap: 6, background: "transparent", border: "none", padding: 0, cursor: "pointer", fontSize: 12.5, fontWeight: 500, color: "var(--cardinal-700)", fontFamily: "var(--font-sans)" }}>
                See paths in your network map<Icon name="arrow" size={13}/>
              </button>
            </div>
          </div>
        )}

        <div>
          <SectionLabel style={{ marginBottom: 8 }}>Source</SectionLabel>
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <SourceChip source={e.source}/>
            {e.source.authority === "inferred" && (
              <span style={{ fontSize: 12, color: "var(--fg-3)" }}>Read by the agent, not confirmed by the organizer.</span>
            )}
          </div>
        </div>
      </div>

      <div style={{ display: "flex", gap: 8, padding: "14px 20px", borderTop: "1px solid var(--ink-100)", background: "#fff" }}>
        <Button variant="primary" size="md" icon="external" disabled={e.closed}>{e.closed ? "Registration closed" : "Register on event page"}</Button>
        <Button variant="secondary" size="md" icon="calendar">Add to calendar</Button>
      </div>
    </div>
  </div>
);

// ---- Tracked view: status pipeline (case E) ----
const EvTracked = ({ onOpen }) => (
  <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
    <AgentNote time="today">
      Your Stripe info session is on the calendar for Tuesday. The NYC fair's registration deadline is Friday, I added a reminder. After the Figma meetup I moved 2 people you met into intro targets.
    </AgentNote>
    {EV_TRACKED.map(t => {
      const e = EVENTS.find(x => x.id === t.id);
      const title = e ? e.title : t.title;
      const meta = e ? `${e.when} · ${e.venue}` : t.co;
      const st = EV_STATUS_META[t.status];
      return (
        <Panel key={t.id} pad={16} style={{ display: "flex", alignItems: "center", gap: 16, opacity: t.done ? 0.72 : 1 }}>
          <div style={{ flex: 1, minWidth: 0, cursor: e ? "pointer" : "default" }} onClick={() => e && onOpen(t.id)}>
            <div style={{ fontFamily: "var(--font-display)", fontSize: 16, fontWeight: 500 }}>{title}</div>
            <div style={{ fontSize: 12.5, color: "var(--fg-2)", marginTop: 2 }}>{meta}</div>
            <div style={{ fontSize: 12, color: "var(--fg-3)", marginTop: 5, display: "flex", alignItems: "center", gap: 5 }}><Icon name="clock" size={12}/>{t.next}</div>
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 4, flexShrink: 0 }}>
            {EV_PIPELINE.map((s, i) => {
              const reached = EV_PIPELINE.indexOf(t.status) >= i;
              const current = t.status === s;
              return (
                <React.Fragment key={s}>
                  {i > 0 && <span style={{ width: 14, height: 1, background: reached ? "var(--cardinal)" : "var(--ink-100)" }}/>}
                  <span title={EV_STATUS_META[s].label} style={{
                    width: current ? 10 : 7, height: current ? 10 : 7, borderRadius: 999,
                    background: reached ? "var(--cardinal)" : "var(--ink-100)",
                    outline: current ? "3px solid var(--cardinal-50)" : "none",
                  }}/>
                </React.Fragment>
              );
            })}
            <Chip tone={st.tone}>{st.label}</Chip>
          </div>
        </Panel>
      );
    })}
  </div>
);

// ---- Empty + locked states (cases F1, gating) ----
const EvEmpty = ({ note }) => (
  <div style={{ border: "1.5px dashed rgba(31,27,22,0.16)", borderRadius: 12, padding: "26px 24px", textAlign: "center", marginBottom: 26 }}>
    <div style={{ fontSize: 13.5, color: "var(--fg-2)", maxWidth: 480, margin: "0 auto", lineHeight: 1.5 }}>{note}</div>
  </div>
);

const EvLocked = ({ count }) => (
  <Panel pad={22} style={{ display: "flex", alignItems: "center", gap: 16 }}>
    <span style={{ width: 40, height: 40, borderRadius: 10, background: "var(--cardinal-50)", color: "var(--cardinal-700)", display: "inline-flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
      <Icon name="lock" size={18}/>
    </span>
    <div style={{ flex: 1 }}>
      <div style={{ fontFamily: "var(--font-display)", fontSize: 16, fontWeight: 500 }}>{count} profile-matched events this month</div>
      <div style={{ fontSize: 13, color: "var(--fg-2)", marginTop: 3 }}>Free plan covers events at your shortlisted companies. Premium adds the full profile-matched feed, meetups, conferences, and hackathons picked for you.</div>
    </div>
    <Button variant="primary" size="sm" icon="zap">Upgrade</Button>
  </Panel>
);

window.ScrEvents = ScrEvents;
