/* global window, React */

// ====================== Sales Rep persona (current user) ======================
window.ME = window.SALES_REPS[0]; // Andika Pratama - top performer
window.ME_RANK = 1;
window.ME_INITIALS = window.ME.name.split(" ").map(w => w[0]).slice(0, 2).join("");

// ====================== DeviceFrame ======================
window.DeviceFrame = function DeviceFrame({ children }) {
  return (
    <div className="device-frame wf-screen">
      <div className="device-screen">
        <div className="notch"></div>
        {children}
        <div className="home-indicator"></div>
      </div>
    </div>
  );
};

// ====================== Canvas wrapper ======================
window.Canvas = function Canvas({ children }) {
  const Icon = window.Icon;
  return (
    <div className="canvas">
      <div className="canvas-head">
        <div className="canvas-brand">
          <div className="canvas-brand-mark"><Icon.Pulse size={22} /></div>
          <div>
            <div className="canvas-brand-name">SalesPulse Mobile</div>
            <div className="canvas-brand-sub">Sales Rep companion · iOS preview</div>
          </div>
        </div>
        <div className="canvas-meta">
          <strong>{window.COMPANY.shortName}</strong>
          {window.COMPANY.asOf}
        </div>
      </div>
      {children}
    </div>
  );
};

// ====================== StatusBar ======================
window.StatusBar = function StatusBar({ time = "09:41" }) {
  return (
    <div className="status-bar">
      <div className="sb-left">{time}</div>
      <div className="sb-right">
        {/* Signal */}
        <svg width="17" height="11" viewBox="0 0 17 11" fill="none">
          <rect x="0" y="7" width="3" height="4" rx=".5" fill="currentColor"/>
          <rect x="4.5" y="5" width="3" height="6" rx=".5" fill="currentColor"/>
          <rect x="9" y="2.5" width="3" height="8.5" rx=".5" fill="currentColor"/>
          <rect x="13.5" y="0" width="3" height="11" rx=".5" fill="currentColor"/>
        </svg>
        {/* Wifi */}
        <svg width="16" height="11" viewBox="0 0 16 11" fill="none" stroke="currentColor" strokeWidth="1.4">
          <path d="M1 4 Q8 -1 15 4" />
          <path d="M3 6.4 Q8 2.4 13 6.4" />
          <path d="M5.4 8.6 Q8 6.8 10.6 8.6" />
          <circle cx="8" cy="10" r=".6" fill="currentColor"/>
        </svg>
        <div className="battery"><span></span></div>
      </div>
    </div>
  );
};

// ====================== MobileHeader ======================
window.MobileHeader = function MobileHeader({ title, sub, back, onBack, right, eyebrow }) {
  const Icon = window.Icon;
  return (
    <div className="m-header">
      <div className="h-left">
        {back && (
          <button className="icon-btn" onClick={onBack}>
            <Icon.ChevronLeft size={20} />
          </button>
        )}
      </div>
      {eyebrow || sub ? (
        <div className="h-title-row">
          {eyebrow && <span className="eyebrow">{eyebrow}</span>}
          <div className="h-title" style={{ textAlign: "center" }}>{title}</div>
        </div>
      ) : (
        <div className="h-title">{title}</div>
      )}
      <div className="h-right">
        {right}
      </div>
    </div>
  );
};

// ====================== BottomTabBar ======================
window.BottomTabBar = function BottomTabBar({ ctx }) {
  const Icon = window.Icon;
  const tabs = window.MAIN_TABS;
  const active = window.PROFILE_ROUTES.includes(ctx.page) ? "profile" : ctx.page;
  return (
    <div className="bottom-tab">
      {tabs.map((t) => {
        const IconC = Icon[t.icon];
        const isActive = active === t.key;
        return (
          <button key={t.key} className={`tab-item wm-tab ${isActive ? "active" : ""}`} onClick={() => ctx.go(t.key)}>
            <div className="tab-icon"><IconC size={20} /></div>
            <span>{t.label}</span>
          </button>
        );
      })}
    </div>
  );
};

// ====================== Screen wrapper ======================
window.Screen = function Screen({ children, title, sub, back, onBack, right, hideTab, noPad, eyebrow }) {
  return (
    <>
      <window.StatusBar />
      <window.MobileHeader title={title} sub={sub} back={back} onBack={onBack} right={right} eyebrow={eyebrow} />
      <div className={`screen ${hideTab ? "no-tab" : ""} ${noPad ? "no-pad" : ""}`}>
        {children}
      </div>
    </>
  );
};

// ====================== Section heading ======================
window.MSection = function MSection({ title, sub, action, onAction, children }) {
  const Icon = window.Icon;
  return (
    <div className="m-section">
      {(title || action) && (
        <div className="m-section-head">
          <div className="t">{title}{sub && <small>{sub}</small>}</div>
          {action && (
            <button className="a" onClick={onAction}>
              {action} <Icon.ChevronRight size={12} />
            </button>
          )}
        </div>
      )}
      {children}
    </div>
  );
};

// ====================== Avatar ======================
window.Avatar = function Avatar({ initials, tone = "primary", size }) {
  const style = size ? { width: size, height: size, fontSize: size * 0.38 } : null;
  return <div className={`avatar-mini ${tone}`} style={style}>{initials}</div>;
};

// ====================== StatusPill ======================
window.StatusPill = function StatusPill({ tone = "", children, dot }) {
  return (
    <span className={`status-pill ${tone}`}>
      {dot && <span className="pill-dot"></span>}
      {children}
    </span>
  );
};

// ====================== Chip ======================
window.Chip = function Chip({ label, active, onClick }) {
  return (
    <button className={`chip ${active ? "active" : ""}`} onClick={onClick}>{label}</button>
  );
};

// ====================== Segmented control ======================
window.Segmented = function Segmented({ options, value, onChange }) {
  return (
    <div className="segmented">
      {options.map(o => (
        <button key={o.value} className={value === o.value ? "active" : ""} onClick={() => onChange(o.value)}>{o.label}</button>
      ))}
    </div>
  );
};

// ====================== FAB ======================
window.FAB = function FAB({ icon = "Plus", onClick }) {
  const Icon = window.Icon;
  const IconC = Icon[icon];
  return (
    <button className="fab" onClick={onClick}>
      <IconC size={24} />
    </button>
  );
};

// ====================== Mini stat ======================
window.MStat = function MStat({ label, value, delta, tone = "primary", icon, trend = "up" }) {
  const Icon = window.Icon;
  const IconC = icon ? Icon[icon] : null;
  const DeltaIcon = trend === "up" ? Icon.Up : trend === "down" ? Icon.Down : null;
  return (
    <div className={`mstat ${tone}`}>
      {IconC && <div className="mi"><IconC size={16} /></div>}
      <div className="ml">{label}</div>
      <div className="mv">{value}</div>
      {delta && (
        <div className={`md ${trend}`}>
          {DeltaIcon && <DeltaIcon size={10} />}
          {delta}
        </div>
      )}
    </div>
  );
};

// ====================== Sparkline ======================
window.Spark = function Spark({ data = [], color = "var(--primary)", height = 32 }) {
  const w = 100, h = height;
  if (!data.length) return null;
  const max = Math.max(...data), min = Math.min(...data);
  const range = max - min || 1;
  const points = data.map((v, i) => {
    const x = (i / (data.length - 1)) * w;
    const y = h - ((v - min) / range) * (h - 4) - 2;
    return `${x},${y}`;
  }).join(" ");
  const area = `0,${h} ${points} ${w},${h}`;
  return (
    <svg className="spark" viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none">
      <polygon points={area} fill={color} opacity="0.12" />
      <polyline points={points} stroke={color} strokeWidth="1.5" fill="none" strokeLinejoin="round" strokeLinecap="round" />
    </svg>
  );
};

// ====================== Bar chart (mobile) ======================
window.BarChart = function BarChart({ data, valueKey = "actual", labelKey = "m", format = window.fmtShort }) {
  const max = Math.max(...data.map(d => d[valueKey] || 0));
  return (
    <div className="bar-chart">
      {data.map((d, i) => {
        const h = ((d[valueKey] || 0) / max) * 100;
        return (
          <div key={i} className="bar" style={{ height: `${h}%` }}>
            <div className="bar-label">{d[labelKey]}</div>
          </div>
        );
      })}
    </div>
  );
};

// ====================== Line chart (mobile) ======================
window.LineChart = function LineChart({ data, valueKey = "actual", targetKey, labelKey = "m", forecast }) {
  const W = 358, H = 160, P = 24;
  const all = [...data, ...(forecast || [])];
  const max = Math.max(...all.map(d => Math.max(d[valueKey] || 0, d.optimistic || 0, d[targetKey] || 0))) * 1.05;
  const min = 0;
  const xStep = (W - P * 2) / (all.length - 1);
  const yMap = v => H - P - ((v - min) / (max - min)) * (H - P * 2);

  const ptsActual = data.map((d, i) => `${P + i * xStep},${yMap(d[valueKey])}`).join(" ");
  const ptsTarget = targetKey ? data.map((d, i) => `${P + i * xStep},${yMap(d[targetKey])}`).join(" ") : null;

  let ptsForecast = null;
  if (forecast && forecast.length) {
    const startIdx = data.length - 1;
    const lastActual = data[data.length - 1][valueKey];
    const fpts = [[P + startIdx * xStep, yMap(lastActual)], ...forecast.map((d, i) => [P + (startIdx + 1 + i) * xStep, yMap(d.base || d[valueKey])])];
    ptsForecast = fpts.map(p => `${p[0]},${p[1]}`).join(" ");
  }

  // Show only every Nth label to avoid clutter
  const labelStep = Math.ceil(all.length / 6);

  return (
    <svg className="line-chart" viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none">
      <defs>
        <linearGradient id="lcfill-m" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="#0d9488" stopOpacity="0.25" />
          <stop offset="100%" stopColor="#0d9488" stopOpacity="0" />
        </linearGradient>
      </defs>

      {[0.25, 0.5, 0.75, 1].map((f, i) => (
        <line key={i} x1={P} x2={W - P} y1={H - P - f * (H - P * 2)} y2={H - P - f * (H - P * 2)} stroke="#eef2f5" strokeWidth="1" />
      ))}

      <polygon points={`${P},${H - P} ${ptsActual} ${P + (data.length - 1) * xStep},${H - P}`} fill="url(#lcfill-m)" />
      <polyline points={ptsActual} stroke="#0d9488" strokeWidth="2" fill="none" strokeLinejoin="round" />

      {ptsTarget && <polyline points={ptsTarget} stroke="#94a3b8" strokeWidth="1.2" fill="none" strokeDasharray="3 3" />}
      {ptsForecast && <polyline points={ptsForecast} stroke="#6366f1" strokeWidth="1.8" fill="none" strokeDasharray="4 3" strokeLinejoin="round" />}

      {data.map((d, i) => (
        <circle key={i} cx={P + i * xStep} cy={yMap(d[valueKey])} r="2.5" fill="#0d9488" stroke="#fff" strokeWidth="1.2" />
      ))}

      {all.map((d, i) => (
        i % labelStep === 0 ? <text key={i} x={P + i * xStep} y={H - 6} fontSize="9" fill="#64748b" textAnchor="middle">{d[labelKey]}</text> : null
      ))}
    </svg>
  );
};

// ====================== Donut ======================
window.Donut = function Donut({ data, total }) {
  const sum = total || data.reduce((a, b) => a + b.value, 0);
  const R = 50, C = 2 * Math.PI * R;
  let offset = 0;
  return (
    <div className="donut-wrap">
      <div className="donut">
        <svg viewBox="0 0 140 140">
          <circle cx="70" cy="70" r={R} fill="none" stroke="#f1f5f9" strokeWidth="14" />
          {data.map((d, i) => {
            const frac = d.value / sum;
            const dash = frac * C;
            const el = (
              <circle key={i} cx="70" cy="70" r={R} fill="none" stroke={d.color} strokeWidth="14"
                strokeDasharray={`${dash} ${C - dash}`} strokeDashoffset={-offset} strokeLinecap="butt" />
            );
            offset += dash;
            return el;
          })}
        </svg>
        <div className="donut-center">
          <div className="v">{window.fmtShort(sum)}</div>
          <div className="l">Total</div>
        </div>
      </div>
      <div className="donut-legend">
        {data.map((d, i) => (
          <div key={i} className="donut-legend-item">
            <span className="swatch" style={{ background: d.color }}></span>
            <span className="name">{d.name}</span>
            <span className="val">{d.pct ? d.pct + "%" : window.fmtShort(d.value)}</span>
          </div>
        ))}
      </div>
    </div>
  );
};

// ====================== Dial ======================
window.Dial = function Dial({ pct, label, sub }) {
  const R = 70, C = 2 * Math.PI * R;
  const fill = Math.min(pct, 100) / 100 * C;
  const color = pct >= 90 ? "#10b981" : pct >= 70 ? "#0d9488" : pct >= 50 ? "#f59e0b" : "#ef4444";
  return (
    <div className="dial">
      <svg viewBox="0 0 180 180">
        <circle cx="90" cy="90" r={R} fill="none" stroke="#f1f5f9" strokeWidth="12" />
        <circle cx="90" cy="90" r={R} fill="none" stroke={color} strokeWidth="12"
          strokeDasharray={`${fill} ${C - fill}`} strokeLinecap="round" />
      </svg>
      <div className="dial-center">
        <div className="pct" style={{ color }}>{pct.toFixed(1)}%</div>
        <div className="lbl">{label}</div>
        {sub && <div className="sub">{sub}</div>}
      </div>
    </div>
  );
};
