// Dashboard principal: compone los bloques en tres variantes de layout.
// V1 "Ejecutiva" — overview limpio en una columna
// V2 "Aireada modular" — hero premium oscuro + cards modulares
// V3 "Análisis profundo" — densidad alta, más data viz

const Dashboard = ({ variant = "v1", data, tweaks = {} }) => {
  const wrap = {
    padding: variant === "v3" ? "40px" : "48px 56px 56px",
    background: "var(--bg-base)",
    fontFamily: "var(--font-body)",
    color: "#000",
    minWidth: 1280,
  };
  // V2 = dark hero
  // V1 = light hero
  // V3 = compact dense

  const showTrust = tweaks.showTrustpilot !== false;
  const dataFiltered = {
    ...data,
    stores: showTrust ? data.stores : data.stores.filter(s => s.id !== "trustpilot"),
  };

  if (variant === "v2") return <DashboardV2 data={dataFiltered} tweaks={tweaks} wrap={wrap} />;
  if (variant === "v3") return <DashboardV3 data={dataFiltered} tweaks={tweaks} wrap={wrap} />;
  return <DashboardV1 data={dataFiltered} tweaks={tweaks} wrap={wrap} />;
};

// ─── V1 · Ejecutiva ─────────────────────────────────────────────────
const DashboardV1 = ({ data, tweaks, wrap }) => (
  <div style={wrap}>
    <HeroSummary data={data} dark={false} />
    <div style={{ height: 32 }} />
    <Block1Rating data={data} />
    <div style={{ marginTop: 16 }}>
      <StarsDistributionCard data={data} />
    </div>
    <Block2Downloads data={data} splitChart={tweaks.splitChart || "donut"} />
    <Block3Reviews data={data} />
    <div style={{ marginTop: 16 }}>
      <TopicHeatmapCard data={data} />
    </div>
    {tweaks.showExtras !== false && (
      <div style={{ marginTop: 56 }}>
        <ResponseStatsCard data={data} />
      </div>
    )}
    <FooterNote />
  </div>
);

// ─── V2 · Aireada modular (hero premium oscuro) ────────────────────
const DashboardV2 = ({ data, tweaks, wrap }) => (
  <div style={wrap}>
    <HeroSummary data={data} dark={true} />

    <div style={{ height: 40 }} />

    {/* Bloque 1: cards de store en columna gruesa, evolución a la derecha */}
    <section data-screen-label="01 Rating de las stores">
      <SectionTitle index={1} title="Rating de las stores"
        sub="Nota actual y tendencia diaria de cada tienda." />
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 16 }}>
        {data.stores.map(s => <StoreRatingCard key={s.id} store={s} />)}
      </div>
      <div style={{ marginTop: 16 }}>
        <Card>
          <CardHeader eyebrow="EVOLUCIÓN 12 SEMANAS" title="Nota media por store" />
          <LineChart
            height={260}
            yDomain={[3.5, 5]} yTicks={3}
            yFormat={(v) => v.toFixed(1).replace(".", ",")}
            series={[
              { name: "App Store", color: "var(--chart-1)",
                data: data.stores[0].weeks.map((y, i) => ({ x: `S${i + 10}`, y })) },
              { name: "Google Play", color: "var(--chart-3)",
                data: data.stores[1].weeks.map((y, i) => ({ x: `S${i + 10}`, y })) },
              ...(data.stores[2] ? [{ name: "Trustpilot", color: "var(--chart-2)",
                data: data.stores[2].weeks.map((y, i) => ({ x: `S${i + 10}`, y })) }] : []),
            ]}
          />
        </Card>
      </div>
    </section>

    <Block2Downloads data={data} splitChart={tweaks.splitChart || "bar"} />

    {/* Reseñas críticas como grid de cards (no master-detail) */}
    <section data-screen-label="03 Reseñas críticas" style={{ marginTop: 56 }}>
      <SectionTitle index={3} title="Reseñas críticas por categoría"
        sub="Cada tarjeta agrupa las reseñas más negativas de la semana." />
      <div style={{ display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 16 }}>
        {data.criticalCategories.slice(0, 6).map(c => <ReviewMiniCard key={c.id} c={c} />)}
      </div>
    </section>

    <div style={{ height: 56 }} />
    <ResponseStatsCard data={data} />

    <FooterNote />
  </div>
);

const ReviewMiniCard = ({ c }) => {
  const status = STATUS_TONES[c.status] || STATUS_TONES.estable;
  const delta = c.count - c.countPrev;
  return (
    <Card>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 12 }}>
        <div>
          <Pill tone={status.tone} style={{ marginBottom: 10 }}>{status.label}</Pill>
          <div style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 18 }}>{c.name}</div>
        </div>
        <div style={{ textAlign: "right" }}>
          <div style={{ fontFamily: "var(--font-num)", fontSize: 32, fontWeight: 800, color: "#000", lineHeight: 1 }}>{c.count}</div>
          <div style={{ marginTop: 6 }}><Delta value={delta} invert /></div>
        </div>
      </div>
      <div style={{ marginTop: 16, padding: 16, background: "var(--grey-50)", borderRadius: 12 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 8 }}>
          <Stars value={c.sampleStars} size={11} />
          <span style={{ fontSize: 10, color: "var(--grey-700)", fontWeight: 700, textTransform: "uppercase", letterSpacing: ".06em" }}>
            {c.sampleStore} · {c.sampleDate}
          </span>
        </div>
        <p style={{ margin: 0, fontSize: 13, color: "#000", lineHeight: 1.45, fontWeight: 500 }}>
          “{c.sample.length > 140 ? c.sample.slice(0, 140) + "…" : c.sample}”
        </p>
      </div>
      <div style={{ marginTop: 14, display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <span style={{ fontSize: 11, color: "var(--grey-700)" }}>★ media: <strong style={{ color: "#000", fontFamily: "var(--font-num)" }}>{c.avgStars.toFixed(1).replace(".", ",")}</strong></span>
        <button style={{ ...btn.ghost, height: 28, fontSize: 11, padding: "0 10px" }}>Ver {c.count} reseñas →</button>
      </div>
    </Card>
  );
};

// ─── V3 · Análisis profundo (denso, BI-style) ───────────────────────
const DashboardV3 = ({ data, tweaks, wrap }) => (
  <div style={{ ...wrap, padding: "32px 40px 40px" }}>
    <HeroSummary data={data} dark={false} />

    <div style={{ height: 24 }} />

    {/* Fila 1: rating cards compactas + sparkline evolución */}
    <section data-screen-label="01 Rating de las stores">
      <SectionTitle index={1} title="Rating de las stores" />
      <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr) 1.2fr", gap: 12 }}>
        {data.stores.map(s => <CompactStoreCard key={s.id} store={s} />)}
        <Card>
          <CardHeader eyebrow="EVOLUCIÓN" title="Nota media · 12 sem" />
          <LineChart
            height={180} yDomain={[3.5, 5]} yTicks={3}
            yFormat={(v) => v.toFixed(1).replace(".", ",")}
            series={[
              { name: "App Store", color: "var(--chart-1)",
                data: data.stores[0].weeks.map((y, i) => ({ x: `S${i + 10}`, y })) },
              { name: "Google Play", color: "var(--chart-3)",
                data: data.stores[1].weeks.map((y, i) => ({ x: `S${i + 10}`, y })) },
              ...(data.stores[2] ? [{ name: "Trustpilot", color: "var(--chart-2)",
                data: data.stores[2].weeks.map((y, i) => ({ x: `S${i + 10}`, y })) }] : []),
            ]}
          />
        </Card>
      </div>

      {/* Distribución de estrellas */}
      <div style={{ marginTop: 12 }}>
        <StarsDistributionCard data={data} />
      </div>
    </section>

    {/* Fila 2: descargas */}
    <section data-screen-label="02 Descargas" style={{ marginTop: 32 }}>
      <SectionTitle index={2} title="Descargas por sistema operativo" />
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
        <Card>
          <CardHeader eyebrow="TOTALES" title="Esta semana" />
          <div style={{ fontFamily: "var(--font-num)", fontSize: 48, fontWeight: 900, color: "#000", lineHeight: 1 }}>
            {fmt(data.downloads.totalWeek)}
          </div>
          <div style={{ marginTop: 8 }}>
            <Delta value={+(((data.downloads.totalWeek - data.downloads.totalWeekPrev) / data.downloads.totalWeekPrev) * 100).toFixed(1)} suffix=" %" />
          </div>
          <div style={{ marginTop: 16, display: "flex", flexDirection: "column", gap: 12 }}>
            <SOMetricCompact color="var(--chart-3)" label="iOS" value={data.downloads.ios} prev={data.downloads.iosPrev} />
            <SOMetricCompact color="var(--chart-1)" label="Android" value={data.downloads.android} prev={data.downloads.androidPrev} />
          </div>
        </Card>
        <Card>
          <CardHeader eyebrow="REPARTO" title="iOS vs Android" />
          <div style={{ display: "flex", justifyContent: "center", paddingTop: 16 }}>
            <DonutChart ios={data.downloads.ios} android={data.downloads.android} size={180} />
          </div>
        </Card>
      </div>
    </section>

    {/* Fila 3: reseñas + heatmap */}
    <section data-screen-label="03 Reseñas críticas" style={{ marginTop: 32 }}>
      <SectionTitle index={3} title="Reseñas críticas" />
      <div style={{ display: "grid", gridTemplateColumns: "1fr", gap: 12 }}>
        <ReviewTable data={data} active={data.criticalCategories[0].id} onActive={() => {}} />
        <TopicHeatmapCard data={data} />
      </div>
    </section>

    {/* Fila 4: impacto versiones + sentiment + response */}
    <section style={{ marginTop: 32 }}>
      <SectionTitle index={4} title="KPIs adicionales" sub="Atención e impacto por versión." />
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
        <ResponseStatsCard data={data} />
        <VersionImpactCard data={data} />
      </div>
    </section>

    <FooterNote />
  </div>
);

const CompactStoreCard = ({ store }) => {
  const dRating = +(store.rating - store.ratingPrev).toFixed(1);
  return (
    <Card style={{ padding: 18 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 12 }}>
        <StoreLogo id={store.id} />
        <div>
          <div style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 14 }}>{store.name}</div>
          <div style={{ fontSize: 10, color: "var(--grey-700)", textTransform: "uppercase", fontWeight: 600, letterSpacing: ".08em" }}>{store.sub}</div>
        </div>
      </div>
      <div style={{ display: "flex", alignItems: "baseline", gap: 6 }}>
        <span style={{ fontFamily: "var(--font-num)", fontSize: 40, fontWeight: 900, lineHeight: 1, color: "#000" }}>
          {store.rating.toFixed(1).replace(".", ",")}
        </span>
        <span style={{ fontFamily: "var(--font-num)", fontSize: 14, color: "var(--grey-700)", fontWeight: 700 }}>/ 5</span>
      </div>
      <div style={{ marginTop: 6 }}><Delta value={dRating} /></div>
      <div style={{ marginTop: 10 }}>
        <Sparkline data={store.daily} w={220} h={36} color="var(--brand-blue)" />
      </div>
      <div style={{ marginTop: 12, paddingTop: 10, borderTop: "1px solid var(--grey-100)", display: "flex", justifyContent: "space-between", fontSize: 11 }}>
        <span style={{ color: "var(--grey-700)" }}>Valoraciones · <strong style={{ color: "#000", fontFamily: "var(--font-num)" }}>{fmt(store.reviews)}</strong></span>
        <Delta value={store.reviewsDelta} size={11} />
      </div>
    </Card>
  );
};

const SOMetricCompact = ({ color, label, value, prev }) => {
  const delta = +(((value - prev) / prev) * 100).toFixed(1);
  return (
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "10px 0", borderTop: "1px solid var(--grey-100)" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
        <span style={{ width: 8, height: 8, background: color, borderRadius: 2 }} />
        <span style={{ fontSize: 11, fontWeight: 700, color: "var(--grey-700)", textTransform: "uppercase", letterSpacing: ".06em" }}>{label}</span>
      </div>
      <div style={{ display: "flex", alignItems: "baseline", gap: 8 }}>
        <span style={{ fontFamily: "var(--font-num)", fontSize: 16, fontWeight: 800 }}>{fmt(value)}</span>
        <Delta value={delta} suffix=" %" size={11} />
      </div>
    </div>
  );
};

Object.assign(window, { Dashboard, DashboardV1, DashboardV2, DashboardV3 });
