// GuestMaker CRM B2B · analytics · four views, one query.

const AN_RANGES = ["7D", "30D", "90D", "12M"];

const AN_OVERVIEW = {
  open: 470000, weighted: 214300, conversion: 46.2, convPrev: 39.8, cycle: 54, cyclePrev: 61,
  created: [3, 5, 2, 6, 4, 7, 5, 3, 6, 8, 4, 5],
  won: [1, 2, 0, 2, 1, 3, 1, 0, 2, 3, 1, 2],
  lost: [0, 1, 1, 0, 2, 1, 0, 1, 1, 0, 2, 1],
  weeks: ["W23","W24","W25","W26","W27","W28","W29","W30","W31","W32","W33","W34"],
  lossReasons: [["Price", 6], ["No response", 4], ["Competitor", 3], ["Availability", 2], ["Event cancelled", 1], ["Other", 1]],
  split: [["Corporate / FIT", 356000, FUCHSIA], ["Groups & Events", 231500, VIOLET]],
};
const AN_FUNNEL = [
  { stage: "Qualification", count: 3, value: 172000, days: 15.5, conv: 67 },
  { stage: "RFP Received",  count: 2, value: 70000,  days: 8.0,  conv: 150 },
  { stage: "Proposal Sent", count: 3, value: 124500, days: 14.6, conv: 33 },
  { stage: "Quote Sent",    count: 1, value: 37500,  days: 8.5,  conv: 400 },
  { stage: "Negotiation",   count: 4, value: 298000, days: 7.3,  conv: null },
];
const AN_FORECAST = [["Aug 26", 60700], ["Sep 26", 188600], ["Oct 26", 10400], ["Nov 26", 74300], ["Dec 26", 32800], ["Jan 27", 18900]];
const AN_TEAM = {
  overdue: 2, sent: 125, openRate: 80.8, clickRate: 29.6,
  board: [
    { who: "ko", wonEur: 108000, won: 2, open: 1, act: 0, share: 46 },
    { who: "ml", wonEur: 84000,  won: 1, open: 2, act: 0, share: 36 },
    { who: "da", wonEur: 42000,  won: 1, open: 0, act: 0, share: 18 },
    { who: "yf", wonEur: 0,      won: 0, open: 2, act: 5, share: 0 },
  ],
  acts: [["Email", 3], ["Call", 2], ["Virtual meeting", 2], ["Task", 1]],
  funnel: [["Sent", 125], ["Opened", 101], ["Clicked", 37]],
};
const AN_PROD = {
  newAccounts: 9, coverage: 100, miceWon: 94000, commissionCost: 130900, penalties: 0,
  ledger: [["Accrued", 35200, FUCHSIA], ["Invoiced", 28600, VIOLET], ["Settled", 67100, GREEN], ["Cancelled", 0, RED]],
  top: [["tuig", 179200, 655, 78], ["vec", 138500, 438, 64], ["cwt", 111400, 349, 42], ["amex", 98000, 302, 51],
        ["iber", 84000, 288, 66], ["tuies", 76500, 241, 33], ["kuoni", 74000, 168, 24], ["pfz", 61400, 142, 19]],
  rnByMonth: [["Sep", 1824], ["Oct", 380], ["Nov", 1504], ["Dec", 737], ["Jan", 612], ["Feb", 1180],
              ["Mar", 940], ["Apr", 1320], ["May", 1610], ["Jun", 1780], ["Jul", 2040], ["Aug", 1120]],
};

function AnCard({ title, sub, children, right, span }) {
  return (
    <div style={{ background: SURFACE, border: `1px solid ${RULE}`, borderRadius: 10, padding: "13px 15px 15px", gridColumn: span ? `span ${span}` : "auto" }}>
      <div style={{ display: "flex", alignItems: "flex-start", gap: 10, marginBottom: 12 }}>
        <div style={{ flex: 1 }}>
          <h4 style={{ fontFamily: SERIF, fontSize: 15.5, fontWeight: 500, margin: 0, letterSpacing: "-0.01em" }}>{title}</h4>
          {sub && <Mono size={9} color={FAINT} style={{ letterSpacing: "0.14em", fontWeight: 600, display: "block", marginTop: 3 }}>{sub.toUpperCase()}</Mono>}
        </div>
        {right}
      </div>
      {children}
    </div>
  );
}
function BarRow({ label, value, max, display, color = FUCHSIA, meta, rank }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 9, padding: "6px 0" }}>
      {rank != null && <Mono size={9.5} color={FAINT} style={{ width: 12 }}>{rank}</Mono>}
      <span style={{ width: 118, fontSize: 11.5, fontWeight: 500, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{label}</span>
      <div style={{ flex: 1, height: 7, borderRadius: 999, background: PAPER, border: `1px solid ${RULE_SOFT}`, overflow: "hidden" }}>
        <div style={{ height: "100%", width: `${Math.max(2, (value / max) * 100)}%`, background: `linear-gradient(90deg,${color}bb,${color})`, borderRadius: 999 }} />
      </div>
      {meta && <Mono size={9.5} color={FAINT} style={{ width: 62, textAlign: "right" }}>{meta}</Mono>}
      <Mono size={11} color={INK} style={{ fontWeight: 700, width: 58, textAlign: "right" }}>{display}</Mono>
    </div>
  );
}
function Columns({ data, color = FUCHSIA, height = 128, fmt = v => eur(v) }) {
  const max = Math.max(...data.map(d => d[1])) || 1;
  return (
    <div style={{ display: "flex", alignItems: "flex-end", gap: 8, height, paddingTop: 16 }}>
      {data.map(([l, v]) => (
        <div key={l} style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", gap: 5, height: "100%", justifyContent: "flex-end" }}>
          <Mono size={9} color={DIM} style={{ fontWeight: 600 }}>{fmt(v)}</Mono>
          <div style={{ width: "100%", height: `${(v / max) * 100}%`, minHeight: 3, background: `linear-gradient(180deg,${color},${color}77)`, borderRadius: "3px 3px 0 0" }} />
          <Mono size={9} color={FAINT}>{l}</Mono>
        </div>
      ))}
    </div>
  );
}

function B2BAnalyticsPanel({ embedded }) {
  const [view, setView] = useState("overview");
  const [range, setRange] = useState("12M");
  const [pipe, setPipe] = useState("all");
  const [owner, setOwner] = useState("all");
  const VIEWS = [["overview", "Overview", "chart"], ["pipeline", "Pipeline", "layers"], ["team", "Team", "users"], ["production", "Production", "bed"]];
  const funnelMax = Math.max(...AN_FUNNEL.map(f => f.value));

  return (
    <div style={{ fontFamily: SANS }}>
      <div style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap", marginBottom: 14 }}>
        <div style={{ display: "flex", gap: 16, flex: 1 }}>
          {VIEWS.map(([k, l, ic]) => (
            <button key={k} onClick={() => setView(k)} style={{
              display: "inline-flex", alignItems: "center", gap: 6, padding: "0 1px 7px", background: "none", cursor: "pointer",
              border: "none", borderBottom: `2px solid ${view === k ? FUCHSIA : "transparent"}`,
              color: view === k ? INK : DIM, fontFamily: SANS, fontSize: 12.5, fontWeight: view === k ? 600 : 500,
            }}><Icon name={ic} size={12} color={view === k ? FUCHSIA : FAINT} />{l}</button>
          ))}
        </div>
        <Select value={pipe} width={140} onChange={setPipe} options={[{ v: "all", l: "All pipelines" }, ...PIPELINES.map(p => ({ v: p.id, l: p.label }))]} />
        <Select value={owner} icon="user" width={140} onChange={setOwner} options={[{ v: "all", l: "All owners" }, ...USERS.map(u => ({ v: u.id, l: u.name }))]} />
        <span style={{ display: "inline-flex", border: `1px solid ${RULE}`, borderRadius: 7, overflow: "hidden", background: SURFACE }}>
          {AN_RANGES.map(r => (
            <button key={r} onClick={() => setRange(r)} style={{
              padding: "0 10px", height: 30, border: "none", cursor: "pointer", fontFamily: MONO, fontSize: 10.5, fontWeight: 700,
              background: range === r ? INK : "transparent", color: range === r ? "#fff" : DIM,
            }}>{r}</button>
          ))}
        </span>
        <ChromeButton icon="refresh">Refresh</ChromeButton>
      </div>

      {view === "overview" && (
        <div style={{ display: "grid", gap: 10 }}>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 10 }}>
            <KpiTile label="Open pipeline" value={eur(AN_OVERVIEW.open)} sub="14 open deals · both pipelines" />
            <KpiTile label="Weighted forecast" value={eur(AN_OVERVIEW.weighted)} sub="by stage probability" accent={VIOLET} />
            <KpiTile label="Conversion rate" value={pct(AN_OVERVIEW.conversion)} sub={`▲ ${pct(AN_OVERVIEW.conversion - AN_OVERVIEW.convPrev)} vs previous period`} accent={GREEN} />
            <KpiTile label="Avg sales cycle" value={AN_OVERVIEW.cycle + "d"} sub={`▼ ${AN_OVERVIEW.cyclePrev - AN_OVERVIEW.cycle}d vs previous period`} accent={AMBER} />
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 10 }}>
            <AnCard title="Weekly evolution" sub="created · won · lost">
              <div style={{ display: "flex", alignItems: "flex-end", gap: 6, height: 132 }}>
                {AN_OVERVIEW.weeks.map((w, i) => {
                  const max = 8;
                  return (
                    <div key={w} style={{ flex: 1, display: "flex", flexDirection: "column", justifyContent: "flex-end", gap: 4, height: "100%" }}>
                      <div style={{ display: "flex", gap: 2, alignItems: "flex-end", height: "100%" }}>
                        {[[AN_OVERVIEW.created[i], SLATE], [AN_OVERVIEW.won[i], GREEN], [AN_OVERVIEW.lost[i], RED]].map(([v, c], j) => (
                          <div key={j} style={{ flex: 1, height: `${(v / max) * 100}%`, minHeight: 2, background: c, borderRadius: "2px 2px 0 0", opacity: 0.9 }} />
                        ))}
                      </div>
                      <Mono size={8} color={FAINT} style={{ textAlign: "center" }}>{w}</Mono>
                    </div>
                  );
                })}
              </div>
              <div style={{ display: "flex", gap: 14, marginTop: 10, paddingTop: 9, borderTop: `1px dashed ${RULE}` }}>
                {[["Created", SLATE], ["Won", GREEN], ["Lost", RED]].map(([l, c]) => (
                  <span key={l} style={{ display: "inline-flex", alignItems: "center", gap: 5 }}><Dot color={c} size={6} /><Mono size={10} color={DIM}>{l}</Mono></span>
                ))}
              </div>
            </AnCard>
            <AnCard title="Loss reasons" sub="typed causes · closed period">
              {AN_OVERVIEW.lossReasons.map(([l, v]) => (
                <BarRow key={l} label={l} value={v} max={6} display={v} color={RED} />
              ))}
            </AnCard>
          </div>
          <AnCard title="Corporate versus MICE" sub="open value by pipeline">
            <div style={{ display: "flex", height: 26, borderRadius: 6, overflow: "hidden", border: `1px solid ${RULE}` }}>
              {AN_OVERVIEW.split.map(([l, v, c]) => (
                <div key={l} style={{ width: `${(v / 587500) * 100}%`, background: c, display: "grid", placeItems: "center" }}>
                  <Mono size={9.5} color="#fff" style={{ fontWeight: 700 }}>{eur(v)}</Mono>
                </div>
              ))}
            </div>
            <div style={{ display: "flex", gap: 16, marginTop: 9 }}>
              {AN_OVERVIEW.split.map(([l, v, c]) => (
                <span key={l} style={{ display: "inline-flex", alignItems: "center", gap: 6 }}><Dot color={c} size={7} /><Mono size={10.5} color={DIM}>{l}</Mono></span>
              ))}
            </div>
          </AnCard>
        </div>
      )}

      {view === "pipeline" && (
        <div style={{ display: "grid", gap: 10 }}>
          <div style={{ display: "grid", gridTemplateColumns: "1.35fr 1fr", gap: 10 }}>
            <AnCard title="Stage funnel" sub="open deals · count + value · stage→stage conversion">
              <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 4 }}>
                <Mono size={9} color={FAINT} style={{ letterSpacing: "0.12em", fontWeight: 700 }}>STAGE · COUNT · VALUE</Mono>
                <Mono size={9} color={FAINT} style={{ letterSpacing: "0.12em", fontWeight: 700 }}>AVG DAYS</Mono>
              </div>
              {AN_FUNNEL.map((f, i) => (
                <div key={f.stage}>
                  <div style={{ display: "flex", alignItems: "center", gap: 10, marginTop: 8 }}>
                    <div style={{ flex: 1 }}>
                      <div style={{ display: "flex", alignItems: "baseline", gap: 8 }}>
                        <span style={{ fontSize: 12.5, fontWeight: 600, flex: 1 }}>{f.stage}</span>
                        <Mono size={10.5} color={INK}>{f.count} · {eur(f.value)}</Mono>
                      </div>
                      <div style={{ height: 8, marginTop: 5, borderRadius: 999, background: PAPER, border: `1px solid ${RULE_SOFT}`, overflow: "hidden" }}>
                        <div style={{ height: "100%", width: `${(f.value / funnelMax) * 100}%`, background: `linear-gradient(90deg,${[SLATE, SLATE, VIOLET, VIOLET, FUCHSIA][i]},${FUCHSIA})` }} />
                      </div>
                    </div>
                    <Mono size={11} color={DIM} style={{ width: 40, textAlign: "right" }}>{f.days}d</Mono>
                  </div>
                  {f.conv != null && (
                    <div style={{ display: "inline-flex", alignItems: "center", gap: 4, background: PAPER, border: `1px solid ${RULE}`, borderRadius: 4, padding: "1px 6px", marginTop: 5 }}>
                      <Icon name="arrow-d" size={8} color={f.conv >= 100 ? GREEN : AMBER} />
                      <Mono size={9} color={f.conv >= 100 ? GREEN : AMBER} style={{ fontWeight: 700 }}>{f.conv}%</Mono>
                    </div>
                  )}
                </div>
              ))}
            </AnCard>
            <AnCard title="Forecast by month" sub="weighted value · expected close, next 6 months">
              <Columns data={AN_FORECAST} color={FUCHSIA} height={168} />
            </AnCard>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(2,1fr) 1.6fr", gap: 10 }}>
            <KpiTile label="Rotting deals" value="1" sub="idle past its stage limit" accent={AMBER} />
            <KpiTile label="Avg deal size" value={eur(60400)} sub="won in period" accent={GREEN} />
            <AnCard title="Open versus weighted" sub="unweighted pipeline vs probability-weighted">
              {[["Unweighted open", 470000, SLATE], ["Probability weighted", 214300, FUCHSIA]].map(([l, v, c]) => (
                <BarRow key={l} label={l} value={v} max={470000} display={eur(v)} color={c} />
              ))}
              <Mono size={10} color={FAINT} style={{ display: "block", marginTop: 8, lineHeight: 1.5 }}>
                Weighting uses the probability configured on each stage, which is why editing a stage changes the forecast instantly.
              </Mono>
            </AnCard>
          </div>
        </div>
      )}

      {view === "team" && (
        <div style={{ display: "grid", gap: 10 }}>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 10 }}>
            <KpiTile label="Overdue activities" value={AN_TEAM.overdue} sub="past due, not done" accent={RED} />
            <KpiTile label="Emails sent" value={AN_TEAM.sent} sub="one-to-one, in period" />
            <KpiTile label="Open rate" value={pct(AN_TEAM.openRate)} sub="emails opened" accent={GREEN} />
            <KpiTile label="Click rate" value={pct(AN_TEAM.clickRate)} sub="emails clicked" accent={VIOLET} />
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1.5fr 1fr", gap: 10 }}>
            <AnCard title="Leaderboard" sub="won value in period · top owners">
              <div style={{ display: "flex", justifyContent: "flex-end", gap: 18, marginBottom: 2 }}>
                {["WON €", "WON", "OPEN", "ACT", "SHARE"].map(h => <Mono key={h} size={8.5} color={FAINT} style={{ letterSpacing: "0.1em", fontWeight: 700, width: h === "WON €" ? 44 : 26, textAlign: "right" }}>{h}</Mono>)}
              </div>
              {AN_TEAM.board.map((r, i) => (
                <div key={r.who} style={{ display: "flex", alignItems: "center", gap: 9, padding: "7px 0", borderTop: i ? `1px solid ${RULE_SOFT}` : "none" }}>
                  <Mono size={9.5} color={FAINT} style={{ width: 10 }}>{i + 1}</Mono>
                  <Avatar who={r.who} size={20} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 12, fontWeight: 600, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{USER_BY_ID[r.who].name}</div>
                    <div style={{ height: 5, marginTop: 4, borderRadius: 999, background: PAPER, overflow: "hidden", border: `1px solid ${RULE_SOFT}` }}>
                      <div style={{ height: "100%", width: `${r.share || 1}%`, background: FUCHSIA }} />
                    </div>
                  </div>
                  <Mono size={11} color={INK} style={{ fontWeight: 700, width: 44, textAlign: "right" }}>{eur(r.wonEur)}</Mono>
                  {[r.won, r.open, r.act].map((v, j) => <Mono key={j} size={10.5} color={DIM} style={{ width: 26, textAlign: "right" }}>{v}</Mono>)}
                  <Mono size={10.5} color={FUCHSIA_DARK} style={{ width: 26, textAlign: "right", fontWeight: 700 }}>{r.share}%</Mono>
                </div>
              ))}
            </AnCard>
            <div style={{ display: "grid", gap: 10 }}>
              <AnCard title="Activities" sub="logged in period · by type">
                {AN_TEAM.acts.map(([l, v]) => <BarRow key={l} label={l} value={v} max={3} display={v} color={PLUM} />)}
              </AnCard>
              <AnCard title="Email funnel" sub="sent → opened → clicked">
                {AN_TEAM.funnel.map(([l, v], i) => (
                  <div key={l} style={{ marginBottom: 9 }}>
                    <div style={{ display: "flex", justifyContent: "space-between" }}>
                      <span style={{ fontSize: 11.5, fontWeight: 600 }}>{l}</span>
                      <Mono size={10.5} color={INK} style={{ fontWeight: 700 }}>{v}</Mono>
                    </div>
                    <div style={{ height: 7, marginTop: 4, borderRadius: 999, background: PAPER, border: `1px solid ${RULE_SOFT}`, overflow: "hidden" }}>
                      <div style={{ height: "100%", width: `${(v / 125) * 100}%`, background: `linear-gradient(90deg,${FUCHSIA_DEEP},${FUCHSIA_SOFT})` }} />
                    </div>
                    {i < 2 && (
                      <Mono size={9} color={AMBER} style={{ display: "block", marginTop: 4 }}>
                        ↓ {Math.round((AN_TEAM.funnel[i + 1][1] / v) * 100)}% · −{100 - Math.round((AN_TEAM.funnel[i + 1][1] / v) * 100)}% drop-off
                      </Mono>
                    )}
                  </div>
                ))}
              </AnCard>
            </div>
          </div>
        </div>
      )}

      {view === "production" && (
        <div style={{ display: "grid", gap: 10 }}>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(5,1fr)", gap: 10 }}>
            <KpiTile label="New accounts" value={AN_PROD.newAccounts} sub="created in period" />
            <KpiTile label="Attribution coverage" value={pct(AN_PROD.coverage, 0)} sub="agency reservations matched" accent={GREEN} />
            <KpiTile label="MICE won revenue" value={eur(AN_PROD.miceWon)} sub="won in period" accent={VIOLET} />
            <KpiTile label="Commission cost" value={eur(AN_PROD.commissionCost)} sub="accrued in period" accent={AMBER} />
            <KpiTile label="Penalties collected" value={eur(AN_PROD.penalties)} sub="from cancelled deals" accent={RED} />
          </div>
          <div style={{ background: SURFACE, border: `1px solid ${RULE}`, borderRadius: 10, padding: "11px 14px", display: "flex", alignItems: "center", gap: 12, flexWrap: "wrap" }}>
            <Mono size={9} color={FAINT} style={{ letterSpacing: "0.16em", fontWeight: 700 }}>COMMISSIONS · PERIOD</Mono>
            <div style={{ flex: 1 }} />
            {AN_PROD.ledger.map(([l, v, c]) => (
              <span key={l} style={{ display: "inline-flex", alignItems: "center", gap: 6, background: c + "12", border: `1px solid ${c}44`, borderRadius: 999, padding: "4px 10px" }}>
                <Dot color={c} size={6} />
                <Mono size={10} color={c === RED ? RED : INK} style={{ fontWeight: 600 }}>{l} {eur(v)}</Mono>
              </span>
            ))}
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1.15fr 1fr", gap: 10 }}>
            <AnCard title="Top accounts" sub="by attributed revenue in period · top 8">
              <div style={{ display: "flex", justifyContent: "flex-end", gap: 10, marginBottom: 2 }}>
                <Mono size={8.5} color={FAINT} style={{ letterSpacing: "0.1em", fontWeight: 700, width: 62, textAlign: "right" }}>RN · RES</Mono>
                <Mono size={8.5} color={FAINT} style={{ letterSpacing: "0.1em", fontWeight: 700, width: 58, textAlign: "right" }}>REVENUE</Mono>
              </div>
              {AN_PROD.top.map(([id, rev, rn, res], i) => (
                <BarRow key={id} rank={i + 1} label={ACC_BY_ID[id].name} value={rev} max={179200}
                  display={eur(rev)} meta={`${num(rn)} · ${res}`} color={i === 0 ? FUCHSIA : FUCHSIA_SOFT} />
              ))}
            </AnCard>
            <AnCard title="Room nights" sub="attributed · last 12 months">
              <Columns data={AN_PROD.rnByMonth} color={VIOLET} height={196} fmt={v => num(v)} />
            </AnCard>
          </div>
          <div style={{ display: "flex", alignItems: "flex-start", gap: 9, background: PAPER, border: `1px solid ${RULE}`, borderRadius: 9, padding: "11px 13px" }}>
            <Icon name="spark" size={13} color={FUCHSIA} style={{ marginTop: 1 }} />
            <p style={{ fontSize: 12, color: DIM, lineHeight: 1.55, margin: 0 }}>
              <b style={{ color: INK }}>This is the view a CRM without the reservations inside cannot build.</b> Revenue, room nights,
              ADR and commission cost are not typed in by a sales rep. They are the hotel's own bookings, matched to the account
              that produced them, in the same database.
            </p>
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { B2BAnalyticsPanel, AnCard, BarRow, Columns, AN_PROD, AN_FUNNEL });
