// ============ PRISMA · PANEL CLIENTE — core ============
const { useState, useEffect, useRef, useMemo } = React;

// ---- helpers ----
function hexA(hex, a) {
  const n = parseInt(hex.slice(1), 16);
  const r = (n >> 16) & 255, g = (n >> 8) & 255, b = n & 255;
  return `rgba(${r},${g},${b},${a})`;
}

function useMeasure() {
  const ref = useRef(null);
  const [w, setW] = useState(0);
  useEffect(() => {
    if (!ref.current) return;
    const ro = new ResizeObserver((e) => {
      const cw = e[0].contentRect.width;
      if (cw > 0) setW(cw);
    });
    ro.observe(ref.current);
    return () => ro.disconnect();
  }, []);
  return [ref, w];
}

// ---- accent palette ----
const CL_ACCENT = {
  magenta: '#E8175D', azul: '#3B9EE0', indigo: '#5059A8', teal: '#0D9E8A',
  ok: '#22C55E', warn: '#F59E0B', bad: '#EF4444',
};
const acHex = (k) => CL_ACCENT[k] || '#5059A8';

// ---- status: DB values (available/reserved/sold) <-> display (disponible/reservado/vendido) ----
const DB_TO_DISPLAY = { available: 'disponible', reserved: 'reservado', sold: 'vendido' };
const DISPLAY_TO_DB = { disponible: 'available', reservado: 'reserved', vendido: 'sold' };

const CL_STATUS = {
  disponible: { label: 'Disponible', color: '#22C55E' },
  reservado:  { label: 'Reservado',  color: '#F59E0B' },
  vendido:    { label: 'Vendido',    color: '#EF4444' },
};
const CL_STATUS_CYCLE = ['disponible', 'reservado', 'vendido'];

function clCountStatuses(rows) {
  const c = { disponible: 0, reservado: 0, vendido: 0 };
  rows.forEach(r => r.floors.forEach(f => { c[f.status]++; }));
  return c;
}

// ---- periodos para métricas ----
const CL_PERIODS = [
  { id: 'hoy', label: 'Hoy',      days: 0 },
  { id: '3d',  label: '3 días',   days: 3 },
  { id: '7d',  label: '7 días',   days: 7 },
  { id: '1m',  label: '1 mes',    days: 30 },
  { id: '3m',  label: '3 meses',  days: 90 },
  { id: '6m',  label: '6 meses',  days: 180 },
];

function clRangeStart(periodId) {
  const p = CL_PERIODS.find(x => x.id === periodId);
  if (!p || p.days === 0) {
    const d = new Date();
    d.setHours(0, 0, 0, 0);
    return d.toISOString();
  }
  return new Date(Date.now() - p.days * 86400000).toISOString();
}

// evento tipo → label legible
const CL_TIPO_LABEL = {
  vista_seccion:    'Vista de sección',
  click_unidad:     'Vista de unidad',
  click_whatsapp:   'Click WhatsApp',
  click_pdf:        'Descarga de PDF',
  click_360:        'Recorrido 360°',
  click_piso:       'Vista de piso',
  click_qr:         'Escaneo QR',
};
const CL_TIPO_KIND = {
  vista_seccion: 'view', click_unidad: 'view',
  click_whatsapp: 'whatsapp', click_pdf: 'pdf',
  click_360: 'tour', click_piso: 'view', click_qr: 'pdf',
};

Object.assign(window, {
  hexA, useMeasure, acHex,
  CL_ACCENT, CL_STATUS, CL_STATUS_CYCLE,
  DB_TO_DISPLAY, DISPLAY_TO_DB,
  clCountStatuses, CL_PERIODS, clRangeStart,
  CL_TIPO_LABEL, CL_TIPO_KIND,
});

// ============ icons ============
const Ic = ({ d, size = 18, sw = 1.6, fill = 'none', children, ...p }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill={fill} stroke="currentColor"
       strokeWidth={sw} strokeLinecap="round" strokeLinejoin="round" {...p}>
    {d ? <path d={d} /> : children}
  </svg>
);
const CiDashboard = (p) => <Ic {...p}><rect x="3" y="3" width="7" height="9" rx="1.5"/><rect x="14" y="3" width="7" height="5" rx="1.5"/><rect x="14" y="12" width="7" height="9" rx="1.5"/><rect x="3" y="16" width="7" height="5" rx="1.5"/></Ic>;
const CiAvail    = (p) => <Ic {...p}><path d="M3 7l9-4 9 4-9 4-9-4z"/><path d="M3 12l9 4 9-4"/><path d="M3 17l9 4 9-4"/></Ic>;
const CiChart    = (p) => <Ic {...p}><path d="M4 20V4"/><path d="M4 20h16"/><rect x="7" y="11" width="3" height="6" rx="0.5"/><rect x="12.5" y="7" width="3" height="10" rx="0.5"/><rect x="18" y="13" width="3" height="4" rx="0.5"/></Ic>;
const CiLogout   = (p) => <Ic {...p}><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><path d="M16 17l5-5-5-5"/><path d="M21 12H9"/></Ic>;
const CiChevD    = (p) => <Ic {...p}><path d="M6 9l6 6 6-6"/></Ic>;
const CiCheck    = (p) => <Ic {...p}><path d="M20 6L9 17l-5-5"/></Ic>;
const CiEye      = (p) => <Ic {...p}><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7z"/><circle cx="12" cy="12" r="3"/></Ic>;
const CiHome     = (p) => <Ic {...p}><path d="M3 11l9-7 9 7"/><path d="M5 10v10h14V10"/><path d="M9 20v-6h6v6"/></Ic>;
const CiChat     = (p) => <Ic {...p}><path d="M21 12a8 8 0 0 1-11.5 7.2L4 20l1-4.5A8 8 0 1 1 21 12z"/></Ic>;
const CiTour     = (p) => <Ic {...p}><circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3a14 14 0 0 1 0 18M12 3a14 14 0 0 0 0 18"/></Ic>;
const CiPdf      = (p) => <Ic {...p}><path d="M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8z"/><path d="M14 3v5h5"/></Ic>;
const CiLock     = (p) => <Ic {...p}><rect x="4" y="11" width="16" height="9" rx="2"/><path d="M8 11V8a4 4 0 0 1 8 0v3"/></Ic>;
const CiMail     = (p) => <Ic {...p}><rect x="3" y="5" width="18" height="14" rx="2"/><path d="M4 7l8 6 8-6"/></Ic>;
const CiInfo     = (p) => <Ic {...p}><circle cx="12" cy="12" r="9"/><path d="M12 11v5M12 8h0"/></Ic>;
const CiWarn     = (p) => <Ic {...p}><path d="M10.3 3.6L1.8 18a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 3.6a2 2 0 0 0-3.4 0z"/><path d="M12 9v4M12 17h0"/></Ic>;
const CiBuilding = (p) => <Ic {...p}><rect x="4" y="2.5" width="12" height="19" rx="1.5"/><path d="M16 8h4v13.5"/><path d="M8 6.5h0M11.5 6.5h0M8 10h0M11.5 10h0M8 13.5h0M11.5 13.5h0"/><path d="M8 21.5v-3.5h4v3.5"/></Ic>;
const CiSpinner  = ({ size = 20 }) => (
  <div style={{ width: size, height: size, border: '2px solid rgba(255,255,255,.1)',
    borderTopColor: 'rgba(255,255,255,.6)', borderRadius: '50%',
    animation: 'spin .7s linear infinite' }} />
);

Object.assign(window, {
  CiDashboard, CiAvail, CiChart, CiLogout, CiChevD, CiCheck, CiEye,
  CiHome, CiChat, CiTour, CiPdf, CiLock, CiMail, CiInfo, CiWarn, CiBuilding, CiSpinner,
});

// ============ shared UI components ============

const CiCard = ({ children, style, pad = 18, ...p }) => (
  <div style={{
    background: 'var(--bg-1)', border: '1px solid var(--line)',
    borderRadius: 'var(--r-lg)', padding: pad, ...style,
  }} {...p}>{children}</div>
);

const CiStatCard = ({ label, value, accent, sub, big }) => {
  const c = acHex(accent);
  return (
    <div style={{
      background: 'var(--bg-1)', borderRadius: 'var(--r-lg)',
      border: '1px solid var(--line)', borderTop: '2px solid ' + c,
      padding: '16px 18px 18px', minWidth: 0, flex: 1,
    }}>
      <div style={{ fontSize: 10, fontWeight: 600, letterSpacing: '0.09em',
        textTransform: 'uppercase', color: 'var(--txt-mut)' }}>{label}</div>
      <div style={{
        marginTop: 12, fontWeight: 700, lineHeight: 1.1, color: c,
        fontSize: big ? 40 : String(value).length > 14 ? 12 : String(value).length > 10 ? 14 : String(value).length > 6 ? 18 : 26,
        letterSpacing: '-0.01em',
        whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
      }}>{value}</div>
      {sub && <div style={{ marginTop: 8, fontSize: 12, color: 'var(--txt-mut)',
        display: 'flex', alignItems: 'center', gap: 5 }}>{sub}</div>}
    </div>
  );
};

const CiKicker = ({ children, style }) => (
  <div style={{ fontSize: 10, fontWeight: 600, letterSpacing: '0.10em',
    textTransform: 'uppercase', color: 'var(--txt-dim)', ...style }}>{children}</div>
);

const CiSummaryPill = ({ accentKey, children }) => {
  const c = acHex(accentKey);
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 7,
      background: 'var(--bg-2)', border: '1px solid var(--line)',
      borderRadius: 999, padding: '6px 13px', fontSize: 13, fontWeight: 600,
      color: 'var(--txt)',
    }}>
      <span style={{ width: 7, height: 7, borderRadius: 999, background: c }} />
      {children}
    </span>
  );
};

// ---- SeriesBars ----
const CiSeriesBars = ({ data, color, height = 232, valueLabel = 'visitas', everyLabel = 1 }) => {
  const [ref, w] = useMeasure();
  const [hover, setHover] = useState(null);
  const padL = 30, padR = 10, padT = 14, padB = 26;
  const plotW = Math.max(10, w - padL - padR);
  const plotH = height - padT - padB;
  const max = Math.max(1, ...data.map(d => d.value));
  const niceMax = Math.max(4, Math.ceil(max / 4) * 4);
  const steps = 4;
  const catW = plotW / data.length;
  const barW = Math.min(38, catW * (data.length > 16 ? 0.62 : 0.52));
  const y = (v) => padT + plotH - (v / niceMax) * plotH;

  return (
    <div ref={ref} style={{ position: 'relative', width: '100%', overflow: 'hidden' }}>
      {w === 0 ? <div style={{ height }} /> : null}
      {w > 0 && <svg width={w} height={height} style={{ display: 'block', maxWidth: '100%' }} onMouseLeave={() => setHover(null)}>
        {Array.from({ length: steps + 1 }).map((_, i) => {
          const v = (niceMax / steps) * i;
          return (
            <g key={i}>
              <line x1={padL} x2={w - padR} y1={y(v)} y2={y(v)} stroke="var(--grid)" />
              <text x={padL - 8} y={y(v) + 3.5} textAnchor="end" fontSize="10" fill="var(--txt-dim)" className="u-mono">{Math.round(v)}</text>
            </g>
          );
        })}
        {data.map((d, ci) => {
          const bx = padL + ci * catW + (catW - barW) / 2;
          const by = y(d.value);
          const bh = padT + plotH - by;
          const isHover = hover && hover.ci === ci;
          return (
            <g key={ci}>
              <rect x={bx} y={by} width={barW} height={Math.max(0, bh)} rx={3} fill={color}
                opacity={hover && !isHover ? 0.4 : 1} style={{ transition: 'opacity .12s' }}
                onMouseEnter={() => setHover({ ci, x: bx + barW / 2, y: by, value: d.value, name: d.label })} />
              {ci % everyLabel === 0 &&
                <text x={bx + barW / 2} y={height - 8} textAnchor="middle" fontSize="11" fill="var(--txt-mut)">{d.label}</text>}
            </g>
          );
        })}
      </svg>
      }
      {w > 0 && hover && <CiChartTip x={hover.x} y={hover.y} title={hover.name} value={hover.value + ' ' + valueLabel} cw={w} />}
    </div>
  );
};

const CiChartTip = ({ x, y, title, value, cw }) => {
  const left = Math.min(Math.max(x, 56), cw - 56);
  return (
    <div style={{
      position: 'absolute', left, top: y - 8, transform: 'translate(-50%, -100%)',
      background: '#0b0b0b', border: '1px solid var(--line-strong)', borderRadius: 8,
      padding: '7px 10px', pointerEvents: 'none', whiteSpace: 'nowrap', zIndex: 5,
      boxShadow: '0 8px 24px rgba(0,0,0,.5)',
    }}>
      <div style={{ fontSize: 11, color: 'var(--txt-mut)', marginBottom: 2 }}>{title}</div>
      <div style={{ fontSize: 13, fontWeight: 700 }} className="u-mono">{value}</div>
    </div>
  );
};

Object.assign(window, { CiCard, CiStatCard, CiKicker, CiSummaryPill, CiSeriesBars, CiChartTip });
