// Bloques principales del dashboard: Rating de stores, Descargas por SO, Reseñas críticas.

// ─────────────────────────────────────────────────────────────────────
// BLOQUE 1 · Rating de las stores
// ─────────────────────────────────────────────────────────────────────

const StoreLogo = ({ id }) => {
  if (id === "appstore")   return <div style={{ width: 44, height: 44, borderRadius: 12, background: "#000", color: "#fff", display: "grid", placeItems: "center" }}>{ICONS.appstore}</div>;
  if (id === "playstore")  return <div style={{ width: 44, height: 44, borderRadius: 12, background: "#fff", border: "1px solid var(--grey-100)", display: "grid", placeItems: "center" }}>{ICONS.playstore}</div>;
  if (id === "trustpilot") return <div style={{ width: 44, height: 44, borderRadius: 12, background: "#191919", display: "grid", placeItems: "center" }}>{ICONS.trustpilot}</div>;
  return null;
};

const StoreRatingCard = ({ store, periodLabel, dense = false }) => {
  const dRating = +(store.rating - store.ratingPrev).toFixed(1);
  const dReviews = store.reviewsDelta;
  // Usar historial real si está disponible, si no caer a daily
  const sparkValues = store.fullHistory
    ? store.fullHistory.map(h => h.rating)
    : store.daily;
  const sparkDateFirst = store.fullHistory?.[0]?.date ?? null;
  const sparkDateLast  = store.fullHistory?.[store.fullHistory.length - 1]?.date ?? null;
  return (
    <Card padded={false} style={{ padding: dense ? 20 : 24, display: "flex", flexDirection: "column", gap: dense ? 14 : 18 }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
          <StoreLogo id={store.id} />
          <div>
            <div style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 17, lineHeight: 1.1 }}>{store.name}</div>
            <div style={{ fontSize: 11, color: "var(--grey-700)", fontWeight: 600, textTransform: "uppercase", letterSpacing: ".08em" }}>{store.sub}</div>
          </div>
        </div>
        <button style={{ ...btn.ghost, height: 28, fontSize: 11, padding: "0 10px" }}>Ver detalle</button>
      </div>

      {/* Rating principal */}
      <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 12 }}>
        <div>
          <div style={{ display: "flex", alignItems: "baseline", gap: 6 }}>
            <span style={{ fontFamily: "var(--font-num)", fontSize: 56, fontWeight: 900, letterSpacing: "-0.02em", lineHeight: 1, color: "#000" }}>
              {store.rating.toFixed(1).replace(".", ",")}
            </span>
            <span style={{ fontFamily: "var(--font-num)", fontSize: 18, color: "var(--grey-400)", fontWeight: 600 }}>/ 5</span>
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 6 }}>
            <Stars value={Math.round(store.rating)} size={14} />
            <Delta value={dRating} size={12} />
          </div>
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 4, flexShrink: 0 }}>
          <div style={{ overflow: "hidden", lineHeight: 0, borderRadius: 2 }}>
            <Sparkline data={sparkValues} w={140} h={48} color="var(--brand-blue)" accent />
          </div>
          {sparkDateFirst && (
            <div style={{ display: "flex", justifyContent: "space-between", width: 140 }}>
              <span style={{ fontSize: 9, color: "var(--grey-700)", fontWeight: 700, fontFamily: "var(--font-num)", letterSpacing: ".04em" }}>{sparkDateFirst}</span>
              <span style={{ fontSize: 9, color: "var(--grey-700)", fontWeight: 700, fontFamily: "var(--font-num)", letterSpacing: ".04em" }}>{sparkDateLast}</span>
            </div>
          )}
        </div>
      </div>

      {/* Metricas pie */}
      <div style={{ display: "grid", gridTemplateColumns: store.downloads != null ? "1fr 1fr" : "1fr", gap: 12, borderTop: "1px solid var(--grey-100)", paddingTop: 14 }}>
        <Metric label="Valoraciones" value={fmt(store.reviews)} delta={dReviews} />
        {store.downloads != null && (
          <Metric label="Descargas" value={fmt(store.downloads)} delta={store.downloadsDelta} />
        )}
      </div>
    </Card>
  );
};

const Metric = ({ label, value, delta, suffix = "", invert = false }) => (
  <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
    <span style={{ fontSize: 10, color: "var(--grey-700)", fontWeight: 700, textTransform: "uppercase", letterSpacing: ".08em" }}>{label}</span>
    <div style={{ display: "flex", alignItems: "baseline", gap: 8 }}>
      <span style={{ fontFamily: "var(--font-num)", fontSize: 22, fontWeight: 800, color: "#000" }}>{value}{suffix}</span>
      <Delta value={delta} suffix={suffix === "%" ? " pts" : ""} invert={invert} size={11} />
    </div>
  </div>
);

const Block1Rating = ({ data, dense = false }) => (
  <section data-screen-label="01 Rating de las stores">
    <SectionTitle index={1} title="Rating de las stores"
      sub="Nota global de la app en cada tienda y su evolución."
      right={<StoreTabs />}
    />
    <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 16 }}>
      {data.stores.map(s => <StoreRatingCard key={s.id} store={s} dense={dense} />)}
    </div>

    {/* Evolución agregada */}
    <div style={{ marginTop: 16 }}>
      <Card>
        <CardHeader
          eyebrow="EVOLUCIÓN COMPARADA"
          title="Nota media por store · últimas 12 semanas"
          sub="Cada punto representa el promedio semanal de las valoraciones recibidas en esa semana."
          right={<ChartTypeToggle current="line" />}
        />
        <LineChart
          height={240}
          yTicks={4}
          yFormat={(v) => v.toFixed(1).replace(".", ",")}
          xLabel={(d) => d.x}
          series={data.stores.map((s, i) => ({
            name: s.name,
            color: ["var(--chart-1)", "var(--chart-3)", "var(--chart-2)"][i],
            // Si hay historial real usamos las últimas 12 mediciones con fecha real; si no, weeks con semana genérica
            data: s.fullHistory
              ? s.fullHistory.slice(-12).map(h => ({ x: h.date.slice(0, -3).replace("/", "/"), y: h.rating }))
              : s.weeks.map((y, j) => ({ x: `S${j + 10}`, y })),
          }))}
        />
      </Card>
    </div>
  </section>
);

const StoreTabs = () => {
  const [active, setActive] = React.useState("todas");
  const opts = [["todas", "Todas"], ["appstore", "App Store"], ["playstore", "Google Play"], ["trustpilot", "Trustpilot"]];
  return (
    <div style={{ display: "flex", gap: 6 }}>
      {opts.map(([k, l]) => (
        <button key={k} onClick={() => setActive(k)} style={active === k ? btn.chipActive : btn.chip}>{l}</button>
      ))}
    </div>
  );
};

const ChartTypeToggle = ({ current = "line", onChange = () => {} }) => {
  const [type, setType] = React.useState(current);
  const opts = [["line", "Líneas"], ["bar", "Barras"]];
  return (
    <div style={{ display: "flex", gap: 4, padding: 4, background: "var(--grey-100)", borderRadius: 999 }}>
      {opts.map(([k, l]) => (
        <button key={k} onClick={() => { setType(k); onChange(k); }}
                style={{
                  height: 26, padding: "0 12px", borderRadius: 999,
                  background: type === k ? "#fff" : "transparent",
                  border: 0, fontWeight: 800, fontSize: 11, cursor: "pointer",
                  boxShadow: type === k ? "0 1px 2px rgba(0,0,0,.08)" : "none",
                }}>{l}</button>
      ))}
    </div>
  );
};

// ─────────────────────────────────────────────────────────────────────
// BLOQUE 2 · Descargas por SO
// ─────────────────────────────────────────────────────────────────────

const Block2Downloads = ({ data, splitChart = "donut" }) => {
  const d = data.downloads;
  const total = d.totalWeek;
  const totalDelta = ((d.totalWeek - d.totalWeekPrev) / d.totalWeekPrev) * 100;
  const iosDelta = ((d.ios - d.iosPrev) / d.iosPrev) * 100;
  const andDelta = ((d.android - d.androidPrev) / d.androidPrev) * 100;
  const [split, setSplit] = React.useState(splitChart);

  return (
    <section data-screen-label="02 Descargas por SO" style={{ marginTop: 56 }}>
      <SectionTitle index={2} title="Descargas por sistema operativo"
        sub="Volumen y reparto entre iOS y Android."
      />

      <div style={{ display: "grid", gridTemplateColumns: "1.05fr 1fr", gap: 16 }}>
        {/* KPI principal + sparkline */}
        <Card>
          <CardHeader eyebrow="DESCARGAS TOTALES" title="Esta semana"
            sub="Suma de descargas en App Store y Google Play." />
          <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 16 }}>
            <div>
              <div style={{ fontFamily: "var(--font-num)", fontSize: 72, fontWeight: 900, letterSpacing: "-0.02em", lineHeight: 1, color: "#000" }}>
                {fmt(total)}
              </div>
              <div style={{ marginTop: 10, display: "flex", alignItems: "center", gap: 10 }}>
                <Delta value={+totalDelta.toFixed(1)} suffix=" %" size={13} />
                <span style={{ fontSize: 12, color: "var(--grey-700)" }}>
                  vs sem. anterior · {fmt(d.totalWeekPrev)}
                </span>
              </div>
            </div>
            <div style={{ width: 220 }}>
              <Sparkline data={d.weekly.map(w => w.ios + w.android)} w={220} h={64} color="var(--brand-blue)" accent />
              <div style={{ display: "flex", justifyContent: "space-between", marginTop: 4, fontSize: 10, color: "var(--grey-700)", fontFamily: "var(--font-num)" }}>
                <span>{d.weekly[0].w}</span>
                <span>{d.weekly[d.weekly.length - 1].w}</span>
              </div>
            </div>
          </div>

          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, marginTop: 24, paddingTop: 20, borderTop: "1px solid var(--grey-100)" }}>
            <SOMetric color="var(--chart-3)" label="iOS · App Store" value={d.ios} delta={iosDelta} />
            <SOMetric color="var(--chart-1)" label="Android · Google Play" value={d.android} delta={andDelta} />
          </div>
        </Card>

        {/* Reparto */}
        <Card>
          <CardHeader
            eyebrow="REPARTO POR SO"
            title="iOS vs Android"
            sub="Proporción de descargas de la semana."
            right={
              <div style={{ display: "flex", gap: 4, padding: 4, background: "var(--grey-100)", borderRadius: 999 }}>
                {[["donut", "Donut"], ["bar", "Barras"]].map(([k, l]) => (
                  <button key={k} onClick={() => setSplit(k)}
                          style={{
                            height: 26, padding: "0 12px", borderRadius: 999,
                            background: split === k ? "#fff" : "transparent",
                            border: 0, fontWeight: 800, fontSize: 11, cursor: "pointer",
                            boxShadow: split === k ? "0 1px 2px rgba(0,0,0,.08)" : "none",
                          }}>{l}</button>
                ))}
              </div>
            }
          />
          {split === "donut" ? (
            <div style={{ display: "flex", justifyContent: "center", paddingTop: 8 }}>
              <DonutChart ios={d.ios} android={d.android} size={200} />
            </div>
          ) : (
            <SplitBar ios={d.ios} android={d.android} />
          )}
        </Card>
      </div>
    </section>
  );
};

const SOMetric = ({ color, label, value, delta }) => (
  <div>
    <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
      <span style={{ width: 10, height: 10, borderRadius: 3, background: color }} />
      <span style={{ fontSize: 11, color: "var(--grey-700)", fontWeight: 700, textTransform: "uppercase", letterSpacing: ".08em" }}>{label}</span>
    </div>
    <div style={{ display: "flex", alignItems: "baseline", gap: 10, marginTop: 8 }}>
      <span style={{ fontFamily: "var(--font-num)", fontSize: 28, fontWeight: 800, color: "#000" }}>{fmt(value)}</span>
      <Delta value={+delta.toFixed(1)} suffix=" %" />
    </div>
  </div>
);

const LegendDot = ({ color, label }) => (
  <span style={{ display: "inline-flex", alignItems: "center", gap: 6, color: "var(--grey-700)" }}>
    <span style={{ width: 8, height: 8, background: color, borderRadius: 2 }} />
    {label}
  </span>
);

const SplitBar = ({ ios, android }) => {
  const total = ios + android;
  const fIos = ios / total;
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 16, paddingTop: 16 }}>
      <div style={{ display: "flex", height: 56, borderRadius: 12, overflow: "hidden" }}>
        <div style={{ width: `${fIos * 100}%`, background: "var(--chart-3)", display: "flex", flexDirection: "column", justifyContent: "center", padding: "0 16px", color: "#000" }}>
          <div style={{ fontFamily: "var(--font-num)", fontWeight: 900, fontSize: 18 }}>{fmt(ios)}</div>
          <div style={{ fontSize: 10, fontWeight: 800, textTransform: "uppercase", letterSpacing: ".06em" }}>iOS · {Math.round(fIos * 100)} %</div>
        </div>
        <div style={{ width: `${(1 - fIos) * 100}%`, background: "var(--chart-1)", display: "flex", flexDirection: "column", justifyContent: "center", padding: "0 16px", color: "#fff" }}>
          <div style={{ fontFamily: "var(--font-num)", fontWeight: 900, fontSize: 18 }}>{fmt(android)}</div>
          <div style={{ fontSize: 10, fontWeight: 800, textTransform: "uppercase", letterSpacing: ".06em" }}>Android · {Math.round((1 - fIos) * 100)} %</div>
        </div>
      </div>
      <div style={{ fontSize: 11, color: "var(--grey-700)", textAlign: "center" }}>
        Total: <strong style={{ color: "#000", fontFamily: "var(--font-num)" }}>{fmt(total)}</strong> descargas esta semana.
      </div>
    </div>
  );
};

// ─────────────────────────────────────────────────────────────────────
// BLOQUE 3 · Resumen de reseñas críticas
// ─────────────────────────────────────────────────────────────────────

const STATUS_TONES = {
  recurrente: { tone: "neg", label: "Recurrente" },
  nuevo:      { tone: "warn", label: "Nuevo esta semana" },
  "en mejora":{ tone: "pos", label: "En mejora" },
  estable:    { tone: "neutral", label: "Estable" },
};

const Block3Reviews = ({ data, view = "grid" }) => {
  const [active, setActive] = React.useState(data.criticalCategories[0].id);
  const [vw, setVw] = React.useState(view);
  const cat = data.criticalCategories.find(c => c.id === active);
  return (
    <section data-screen-label="03 Reseñas críticas" style={{ marginTop: 56 }}>
      <SectionTitle index={3} title="Resumen de reseñas críticas"
        sub="Reseñas más críticas de la semana, agrupadas por categoría temática."
        right={
          <div style={{ display: "flex", gap: 4, padding: 4, background: "var(--grey-100)", borderRadius: 999 }}>
            {[["grid", "Grid"], ["table", "Tabla"]].map(([k, l]) => (
              <button key={k} onClick={() => setVw(k)} style={{
                height: 26, padding: "0 12px", borderRadius: 999,
                background: vw === k ? "#fff" : "transparent",
                border: 0, fontWeight: 800, fontSize: 11, cursor: "pointer",
                boxShadow: vw === k ? "0 1px 2px rgba(0,0,0,.08)" : "none",
              }}>{l}</button>
            ))}
          </div>
        }
      />

      {vw === "grid" ? (
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1.2fr", gap: 16 }}>
          {/* Lista categorías */}
          <Card padded={false}>
            <div style={{ padding: "20px 24px 12px", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
              <div style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 15 }}>Categorías ({data.criticalCategories.length})</div>
              <span style={{ fontSize: 11, color: "var(--grey-700)", fontWeight: 500 }}>
                {data.criticalCategories.reduce((a, c) => a + c.count, 0)} reseñas críticas
              </span>
            </div>
            <div style={{ borderTop: "1px solid var(--grey-100)" }}>
              {data.criticalCategories.map(c => (
                <CategoryRow key={c.id} c={c} active={c.id === active} onClick={() => setActive(c.id)} />
              ))}
            </div>
          </Card>

          {/* Detalle reseña representativa */}
          <ReviewDetailCard cat={cat} />
        </div>
      ) : (
        <ReviewTable data={data} active={active} onActive={setActive} />
      )}
    </section>
  );
};

const CategoryRow = ({ c, active, onClick }) => {
  const delta = c.count - c.countPrev;
  const status = STATUS_TONES[c.status] || STATUS_TONES.estable;
  return (
    <button onClick={onClick}
      style={{
        width: "100%", textAlign: "left", padding: "14px 24px",
        background: active ? "var(--grey-50)" : "#fff",
        borderLeft: active ? "3px solid var(--brand-blue)" : "3px solid transparent",
        border: "0", borderBottom: "1px solid var(--grey-100)", cursor: "pointer",
        display: "grid", gridTemplateColumns: "1fr auto auto", alignItems: "center", gap: 14,
        fontFamily: "inherit",
      }}>
      <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
        <span style={{ fontWeight: 700, fontSize: 14, color: "#000" }}>{c.name}</span>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <Pill tone={status.tone} style={{ padding: "2px 6px", fontSize: 9 }}>{status.label}</Pill>
          <span style={{ fontSize: 11, color: "var(--grey-700)", fontWeight: 500 }}>
            ★ media {c.avgStars.toFixed(1).replace(".", ",")}
          </span>
        </div>
      </div>
      <div style={{ textAlign: "right" }}>
        <div style={{ fontFamily: "var(--font-num)", fontSize: 22, fontWeight: 800, color: "#000", lineHeight: 1, marginBottom: 4 }}>{c.count}</div>
        <Delta value={delta} invert size={11} />
      </div>
      <span style={{ color: "var(--grey-400)", marginLeft: 4 }}>›</span>
    </button>
  );
};

const ReviewDetailCard = ({ cat }) => {
  const status = STATUS_TONES[cat.status] || STATUS_TONES.estable;
  const delta = cat.count - cat.countPrev;
  return (
    <Card>
      <div style={{ display: "flex", justifyContent: "space-between", gap: 12, marginBottom: 16 }}>
        <div>
          <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: ".1em", textTransform: "uppercase", color: "var(--grey-700)", marginBottom: 8 }}>
            Reseña representativa
          </div>
          <div style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 20 }}>{cat.name}</div>
        </div>
        <Pill tone={status.tone}>{status.label}</Pill>
      </div>

      {/* Mini stats */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 12, padding: "14px 0", borderTop: "1px solid var(--grey-100)", borderBottom: "1px solid var(--grey-100)" }}>
        <MiniStat label="Reseñas críticas" value={cat.count} delta={delta} invert />
        <MiniStat label="★ media" value={cat.avgStars.toFixed(1).replace(".", ",")} />
        <MiniStat label="Sentimiento" value={cat.sentiment.toFixed(2).replace(".", ",")} sub="rango −1 a +1" />
      </div>

      {/* Quote */}
      <div style={{ marginTop: 18 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 10 }}>
          <Stars value={cat.sampleStars} size={14} />
          <span style={{ fontSize: 11, color: "var(--grey-700)" }}>{cat.sampleStore} · {cat.sampleDate}</span>
        </div>
        <blockquote style={{ margin: 0, fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 18, lineHeight: 1.4, letterSpacing: "-0.005em", color: "#000" }}>
          “{cat.sample}”
        </blockquote>
        <div style={{ marginTop: 10, fontSize: 12, color: "var(--grey-700)" }}>— {cat.sampleAuthor}</div>
      </div>

      <div style={{ marginTop: 20, paddingTop: 16, borderTop: "1px solid var(--grey-100)", display: "flex", gap: 8 }}>
        <button style={btn.primary}>Ver las {cat.count} reseñas</button>
        <button style={btn.ghost}>Asignar a equipo</button>
      </div>
    </Card>
  );
};

const MiniStat = ({ label, value, sub, delta, invert }) => (
  <div>
    <div style={{ fontSize: 10, fontWeight: 700, color: "var(--grey-700)", textTransform: "uppercase", letterSpacing: ".08em" }}>{label}</div>
    <div style={{ display: "flex", alignItems: "baseline", gap: 6, marginTop: 6 }}>
      <span style={{ fontFamily: "var(--font-num)", fontSize: 20, fontWeight: 800, color: "#000" }}>{value}</span>
      {delta != null && <Delta value={delta} invert={invert} size={11} />}
    </div>
    {sub && <div style={{ fontSize: 10, color: "var(--grey-400)", marginTop: 2, fontWeight: 500 }}>{sub}</div>}
  </div>
);

const ReviewTable = ({ data, active, onActive }) => (
  <Card padded={false}>
    <table style={{ width: "100%", borderCollapse: "collapse", fontFamily: "inherit" }}>
      <thead>
        <tr style={{ background: "var(--grey-50)", borderBottom: "1px solid var(--grey-100)" }}>
          {["Categoría", "Reseñas", "Δ vs anterior", "★ media", "Sentimiento", "Estado", "Reseña representativa"].map(h => (
            <th key={h} style={{ textAlign: "left", padding: "12px 16px", fontSize: 10, fontWeight: 700, textTransform: "uppercase", letterSpacing: ".08em", color: "var(--grey-700)" }}>{h}</th>
          ))}
        </tr>
      </thead>
      <tbody>
        {data.criticalCategories.map(c => {
          const status = STATUS_TONES[c.status] || STATUS_TONES.estable;
          const delta = c.count - c.countPrev;
          return (
            <tr key={c.id} onClick={() => onActive(c.id)} style={{ borderBottom: "1px solid var(--grey-100)", cursor: "pointer", background: c.id === active ? "var(--brand-blue-soft)" : "transparent" }}>
              <td style={{ padding: "14px 16px", fontWeight: 700, fontSize: 13 }}>{c.name}</td>
              <td style={{ padding: "14px 16px", fontFamily: "var(--font-num)", fontWeight: 800, fontSize: 16 }}>{c.count}</td>
              <td style={{ padding: "14px 16px" }}><Delta value={delta} invert size={12} /></td>
              <td style={{ padding: "14px 16px", fontFamily: "var(--font-num)", fontWeight: 600 }}>{c.avgStars.toFixed(1).replace(".", ",")}</td>
              <td style={{ padding: "14px 16px", fontFamily: "var(--font-num)", fontWeight: 600, color: "var(--neg-600)" }}>{c.sentiment.toFixed(2).replace(".", ",")}</td>
              <td style={{ padding: "14px 16px" }}><Pill tone={status.tone}>{status.label}</Pill></td>
              <td style={{ padding: "14px 16px", fontSize: 12, color: "var(--grey-700)", maxWidth: 360, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>“{c.sample}”</td>
            </tr>
          );
        })}
      </tbody>
    </table>
  </Card>
);

Object.assign(window, { Block1Rating, Block2Downloads, Block3Reviews, StoreRatingCard, StoreLogo });
