// Grape Elevate — Dashboard (home) screen

const Sparkline = ({ data, color = '#8B5CF6', height = 40, width = 110, fillOpacity = 0.18 }) => {
  if (!data.length) return null;
  const max = Math.max(...data), min = Math.min(...data);
  const span = Math.max(1, max - min);
  const pts = data.map((v, i) => [
    (i / (data.length - 1)) * width,
    height - ((v - min) / span) * (height - 6) - 3,
  ]);
  // Catmull-rom-ish smoothing for a friendly curve.
  const path = pts.map(([x, y], i) => {
    if (i === 0) return `M ${x},${y}`;
    const [px, py] = pts[i - 1];
    const cx = (px + x) / 2;
    return `C ${cx},${py} ${cx},${y} ${x},${y}`;
  }).join(' ');
  const area = `${path} L ${width},${height} L 0,${height} Z`;
  return (
    <svg width={width} height={height} viewBox={`0 0 ${width} ${height}`} aria-hidden="true">
      <defs>
        <linearGradient id={`sg-${color}`} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor={color} stopOpacity={fillOpacity * 2} />
          <stop offset="100%" stopColor={color} stopOpacity="0" />
        </linearGradient>
      </defs>
      <path d={area} fill={`url(#sg-${color})`} />
      <path d={path} stroke={color} strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round" />
      <circle cx={pts[pts.length - 1][0]} cy={pts[pts.length - 1][1]} r="3" fill={color} />
      <circle cx={pts[pts.length - 1][0]} cy={pts[pts.length - 1][1]} r="6" fill={color} opacity="0.18" />
    </svg>
  );
};

const StatCard = ({ icon, label, value, delta, color, series }) => (
  <div className="card stat-card">
    <div className="stat-head">
      <div className="stat-ic" style={{ background: `color-mix(in oklch, ${color} 18%, transparent)`, color }}>{icon}</div>
      <span className="eyebrow">{label}</span>
    </div>
    <div className="stat-body">
      <div className="stat-val">{value.toLocaleString('pt-BR')}</div>
      <div className="stat-delta" style={{ color: delta >= 0 ? 'var(--green)' : 'var(--coral)' }}>
        {delta >= 0 ? <Icons.ArrowUp size={14} /> : <Icons.ArrowDown size={14} />}
        <span>{Math.abs(delta)}%</span>
      </div>
    </div>
    <Sparkline data={series} color={color} width={220} height={48} />
  </div>
);

// Friendly illustrated template tile — simple geometric scene.
const TemplateTile = ({ illust, title, desc, popular, onUse, t }) => (
  <div className="tpl-card">
    <div className="tpl-illust">{illust}</div>
    <div className="tpl-body">
      <div className="row" style={{ justifyContent: 'space-between', marginBottom: 6 }}>
        <h4 className="tpl-title">{title}</h4>
        {popular && <span className="pill pill-pop">★ {t('home.popular')}</span>}
      </div>
      <p className="tpl-desc">{desc}</p>
      <button className="btn btn-sm" onClick={onUse}>
        <Icons.Plus size={14} /> {t('common.use')}
      </button>
    </div>
  </div>
);

const ActivityIcon = ({ kind }) => {
  const map = {
    dm:     { c: 'var(--cyan)',  i: <Icons.Send size={14} /> },
    lead:   { c: 'var(--grape)', i: <Icons.Tag size={14} /> },
    reply:  { c: 'var(--coral)', i: <Icons.Comment size={14} /> },
    follow: { c: 'var(--sun)',   i: <Icons.Heart size={14} /> },
  };
  const m = map[kind] || map.dm;
  return (
    <div className="act-ic" style={{ background: `color-mix(in oklch, ${m.c} 16%, transparent)`, color: m.c }}>
      {m.i}
    </div>
  );
};

function Dashboard({ t, lang, automations, activity, recent, onNav, onCreateFromTemplate }) {
  const totals = {
    followers: activity.followers.reduce((s, x) => s + x, 0),
    dms:       activity.dms.reduce((s, x) => s + x, 0),
    replies:   activity.replies.reduce((s, x) => s + x, 0),
    leads:     activity.leads.reduce((s, x) => s + x, 0),
  };
  const top = automations.filter((a) => a.status === 'live').sort((a, b) => b.runs - a.runs).slice(0, 4);

  return (
    <>
      <style>{dashStyles}</style>
      <div className="page-head">
        <div>
          <h1 className="page-title">{t('home.hello')}, <span className="gradient-text">Fabiano</span> 👋</h1>
          <p className="page-sub">{t('home.subtitle')}</p>
        </div>
        <div className="row">
          <button className="btn"><Icons.Sparkle size={16} /> AI assistant</button>
          <button className="btn btn-primary" onClick={() => onNav('flow')}><Icons.Plus size={16} /> {t('auto.new')}</button>
        </div>
      </div>

      <div className="stat-grid">
        <StatCard icon={<Icons.Follow size={16} />}   label={t('home.stat.followers')} value={totals.followers} delta={18}  color="#8B5CF6" series={activity.followers} />
        <StatCard icon={<Icons.Send size={16} />}     label={t('home.stat.dms')}       value={totals.dms}       delta={24}  color="#06B6D4" series={activity.dms} />
        <StatCard icon={<Icons.Comment size={16} />}  label={t('home.stat.replies')}   value={totals.replies}   delta={32}  color="#FB7185" series={activity.replies} />
        <StatCard icon={<Icons.Tag size={16} />}      label={t('home.stat.leads')}     value={totals.leads}     delta={-6}  color="#F59E0B" series={activity.leads} />
      </div>

      <div className="dash-row">
        <section className="card">
          <div className="row-between" style={{ marginBottom: 12 }}>
            <div>
              <div className="eyebrow">{t('home.quick.title')}</div>
              <h3 className="section-title">{t('home.quick.subtitle')}</h3>
            </div>
          </div>
          <div className="tpl-grid">
            <TemplateTile t={t}
              illust={<IllustComment />}
              title={t('home.quick.tpl1.title')} desc={t('home.quick.tpl1.desc')} popular
              onUse={() => onCreateFromTemplate('comment')} />
            <TemplateTile t={t}
              illust={<IllustStory />}
              title={t('home.quick.tpl2.title')} desc={t('home.quick.tpl2.desc')}
              onUse={() => onCreateFromTemplate('story')} />
            <TemplateTile t={t}
              illust={<IllustWelcome />}
              title={t('home.quick.tpl3.title')} desc={t('home.quick.tpl3.desc')}
              onUse={() => onCreateFromTemplate('follow')} />
          </div>
        </section>

        <section className="card act-card">
          <div className="row-between" style={{ marginBottom: 12 }}>
            <h3 className="section-title">{t('home.activities.title')}</h3>
            <button className="btn-ghost btn btn-sm">Ver tudo</button>
          </div>
          <div className="act-list">
            {recent.map((r, i) => (
              <div className="act-item" key={i}>
                <ActivityIcon kind={r.kind} />
                <div className="act-text">
                  <div><b>{r.who}</b> <span className="soft">{r.what}</span></div>
                  <div className="muted" style={{ fontSize: 12 }}>{r.auto} · {r.when}</div>
                </div>
              </div>
            ))}
          </div>
        </section>
      </div>

      <section className="card">
        <div className="row-between" style={{ marginBottom: 12 }}>
          <h3 className="section-title">{t('home.top.title')}</h3>
          <button className="btn-ghost btn btn-sm" onClick={() => onNav('automations')}>Ver todas <Icons.Chevron size={14} /></button>
        </div>
        <div className="top-list">
          {top.map((a) => (
            <div className="top-row" key={a.id}>
              <div className="top-name">
                <div className="top-emoji">{a.trigger === 'comment' ? '💬' : a.trigger === 'story' ? '📸' : a.trigger === 'follow' ? '➕' : '✉️'}</div>
                <div>
                  <div style={{ fontWeight: 600 }}>{a.name}</div>
                  <div className="muted" style={{ fontSize: 12 }}>{a.runs.toLocaleString('pt-BR')} execuções · {a.conv}% conversão</div>
                </div>
              </div>
              <div className="top-bar"><i style={{ width: `${Math.min(100, a.conv * 2)}%` }} /></div>
              <span className="pill pill-live"><i className="dot" /> {t('auto.status.live')}</span>
            </div>
          ))}
        </div>
      </section>
    </>
  );
}

// Tiny friendly illustrations — geometric shapes only.
const IllustComment = () => (
  <svg viewBox="0 0 220 120" width="100%" height="100%">
    <rect x="0" y="0" width="220" height="120" fill="none" />
    <rect x="14" y="20" width="120" height="50" rx="14" fill="#FFFFFF" opacity=".75" />
    <circle cx="32" cy="45" r="10" fill="#FB7185" />
    <rect x="48" y="38" width="60" height="6" rx="3" fill="#0B1220" opacity=".35" />
    <rect x="48" y="50" width="44" height="5" rx="2.5" fill="#0B1220" opacity=".18" />
    <path d="M28 70 L36 78 L40 70 Z" fill="#FFFFFF" opacity=".75" />
    <rect x="74" y="86" width="120" height="22" rx="11" fill="#8B5CF6" />
    <rect x="84" y="93" width="8" height="8" rx="4" fill="#fff" opacity=".8" />
    <rect x="98" y="94" width="80" height="6" rx="3" fill="#fff" opacity=".9" />
    <circle cx="190" cy="34" r="14" fill="#06B6D4" opacity=".25" />
    <circle cx="200" cy="50" r="6" fill="#F59E0B" opacity=".5" />
  </svg>
);
const IllustStory = () => (
  <svg viewBox="0 0 220 120" width="100%" height="100%">
    <rect x="60" y="14" width="100" height="92" rx="14" fill="#0B1220" />
    <rect x="60" y="14" width="100" height="92" rx="14" fill="url(#gs1)" opacity=".35" />
    <defs>
      <linearGradient id="gs1" x1="0" y1="0" x2="1" y2="1">
        <stop offset="0%" stopColor="#FB7185" /><stop offset="100%" stopColor="#8B5CF6" />
      </linearGradient>
    </defs>
    <rect x="70" y="24" width="80" height="6" rx="3" fill="#fff" opacity=".5" />
    <rect x="78" y="38" width="64" height="62" rx="10" fill="#fff" opacity=".15" />
    <circle cx="110" cy="58" r="12" fill="#fff" opacity=".9" />
    <path d="M105 53 v10 l9 -5 z" fill="#8B5CF6" />
    <rect x="84" y="82" width="52" height="8" rx="4" fill="#fff" opacity=".75" />
    <circle cx="30" cy="62" r="20" fill="#06B6D4" opacity=".25" />
    <circle cx="190" cy="62" r="20" fill="#F59E0B" opacity=".25" />
  </svg>
);
const IllustWelcome = () => (
  <svg viewBox="0 0 220 120" width="100%" height="100%">
    <circle cx="60" cy="60" r="28" fill="#8B5CF6" opacity=".25" />
    <circle cx="60" cy="60" r="20" fill="#8B5CF6" />
    <text x="60" y="66" textAnchor="middle" fill="#fff" fontSize="20" fontWeight="700" fontFamily="Plus Jakarta Sans">F</text>
    <path d="M50 86 q10 6 20 0" stroke="#fff" strokeWidth="2" fill="none" opacity=".7" />
    <rect x="100" y="32" width="106" height="32" rx="16" fill="#FFFFFF" />
    <rect x="112" y="44" width="80" height="8" rx="4" fill="#0B1220" opacity=".35" />
    <path d="M100 50 l-8 6 0 -12 z" fill="#FFFFFF" />
    <rect x="100" y="74" width="78" height="22" rx="11" fill="#06B6D4" />
    <rect x="110" y="81" width="58" height="8" rx="4" fill="#fff" opacity=".85" />
    <circle cx="200" cy="86" r="10" fill="#FB7185" opacity=".7" />
  </svg>
);

const dashStyles = `
.stat-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 14px; }
@media (max-width: 1100px) { .stat-grid { grid-template-columns: repeat(2, 1fr); } }
.stat-card { display: flex; flex-direction: column; gap: 8px; position: relative; overflow: hidden; }
.stat-head { display: flex; align-items: center; gap: 10px; }
.stat-ic { width: 32px; height: 32px; border-radius: 10px; display: inline-flex; align-items: center; justify-content: center; }
.stat-body { display: flex; align-items: baseline; justify-content: space-between; }
.stat-val { font-size: 28px; font-weight: 800; letter-spacing: -0.02em; }
.stat-delta { display: inline-flex; align-items: center; gap: 2px; font-size: 12.5px; font-weight: 700; }

.dash-row { display: grid; grid-template-columns: 2fr 1fr; gap: 14px; }
@media (max-width: 1100px) { .dash-row { grid-template-columns: 1fr; } }
.section-title { margin: 2px 0 0; font-size: 16px; font-weight: 700; letter-spacing: -0.01em; }

.tpl-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px; }
@media (max-width: 900px) { .tpl-grid { grid-template-columns: 1fr; } }
.tpl-card {
  border: 1px solid var(--line);
  border-radius: var(--radius);
  background: var(--surface-2);
  overflow: hidden;
  display: flex; flex-direction: column;
  transition: transform 150ms cubic-bezier(.2,.9,.3,1.1), box-shadow 150ms, border-color 150ms;
}
.tpl-card:hover { transform: translateY(-2px); box-shadow: var(--shadow-pop); border-color: color-mix(in oklch, var(--grape) 30%, var(--line)); }
.tpl-illust { height: 110px; background: linear-gradient(135deg, color-mix(in oklch, var(--grape) 14%, var(--surface)) 0%, color-mix(in oklch, var(--cyan) 12%, var(--surface)) 100%); display: flex; align-items: center; justify-content: center; padding: 10px; }
.tpl-illust svg { max-height: 100%; }
.tpl-body { padding: 14px; display: flex; flex-direction: column; gap: 8px; }
.tpl-title { margin: 0; font-size: 14px; font-weight: 700; letter-spacing: -0.01em; }
.tpl-desc { margin: 0; font-size: 12.5px; color: var(--text-soft); line-height: 1.45; }
.tpl-body .btn { align-self: flex-start; }

.act-card { display: flex; flex-direction: column; }
.act-list { display: flex; flex-direction: column; gap: 12px; }
.act-item { display: flex; gap: 10px; align-items: flex-start; }
.act-ic { width: 28px; height: 28px; border-radius: 9px; display: inline-flex; align-items: center; justify-content: center; flex-shrink: 0; }
.act-text { font-size: 13px; line-height: 1.4; min-width: 0; }

.top-list { display: flex; flex-direction: column; gap: 8px; }
.top-row { display: grid; grid-template-columns: 1.5fr 1fr 110px; gap: 14px; align-items: center; padding: 10px 6px; border-radius: 10px; }
.top-row:hover { background: var(--surface-2); }
.top-name { display: flex; align-items: center; gap: 12px; min-width: 0; }
.top-emoji { width: 36px; height: 36px; border-radius: 10px; background: var(--surface-3); display: flex; align-items: center; justify-content: center; font-size: 18px; }
.top-bar { height: 6px; background: var(--surface-3); border-radius: 999px; overflow: hidden; }
.top-bar i { display: block; height: 100%; background: linear-gradient(90deg, var(--grape), var(--cyan)); border-radius: 999px; }
.pill-live .dot { width: 6px; height: 6px; border-radius: 50%; background: var(--green); box-shadow: 0 0 0 3px color-mix(in oklch, var(--green) 25%, transparent); }
`;

window.Dashboard = Dashboard;
