// Social Dashboard — multi-platform engagement, trending content, daily planner, auto-post.

function SocialView() {
  const [tab, setTab] = useState('overview');

  return (
    <div className="space-y-5">
      <SectionHead
        eyebrow="Module · Social Dashboard"
        title="Social Status & Content Planner"
        sub="ดู engagement 6 platforms · trending content · วางแผน 5 โพสต์ต่อวัน · auto-post ไปทุกช่อง"
        right={
          <Tabs variant="pill" active={tab} onChange={setTab} tabs={[
            { id: 'overview',  label: 'Engagement',  icon: <Icon name="chart"    className="w-3.5 h-3.5" /> },
            { id: 'trending',  label: 'Trending',    icon: <Icon name="fire"     className="w-3.5 h-3.5" /> },
            { id: 'planner',   label: 'Planner 5/วัน', icon: <Icon name="calendar" className="w-3.5 h-3.5" /> },
            { id: 'integrations', label: 'Auto-post', icon: <Icon name="bolt"    className="w-3.5 h-3.5" /> },
          ]} />
        }
      />

      {tab === 'overview'     && <EngagementOverview />}
      {tab === 'trending'     && <TrendingView />}
      {tab === 'planner'      && <ContentPlanner />}
      {tab === 'integrations' && <Integrations />}
    </div>
  );
}

// ============== Platform icons ==============
function PlatformLogo({ id, size = 16 }) {
  const px = { width: size, height: size };
  const styles = {
    ig: <div style={{ ...px, background: 'linear-gradient(45deg, #FFDC80, #FCB045, #FD1D1D, #C13584, #833AB4, #5851DB)' }} className="rounded-md flex items-center justify-center">
          <svg viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2.5" className="w-2/3 h-2/3"><rect x="3" y="3" width="18" height="18" rx="5"/><circle cx="12" cy="12" r="4"/><circle cx="17.5" cy="6.5" r="0.8" fill="white"/></svg>
        </div>,
    tt: <div style={{ ...px, background: '#000' }} className="rounded-md flex items-center justify-center text-white font-bold" >
          <span style={{ fontSize: size * 0.6 }}>♪</span>
        </div>,
    fb: <div style={{ ...px, background: '#1877F2' }} className="rounded-md flex items-center justify-center text-white font-bold" >
          <span style={{ fontSize: size * 0.7 }}>f</span>
        </div>,
    th: <div style={{ ...px, background: '#000' }} className="rounded-md flex items-center justify-center text-white font-bold" >
          <span style={{ fontSize: size * 0.55 }}>@</span>
        </div>,
    l8: <div style={{ ...px, background: '#FFB400' }} className="rounded-md flex items-center justify-center text-white font-bold" >
          <span style={{ fontSize: size * 0.5 }}>🍋</span>
        </div>,
    yt: <div style={{ ...px, background: '#FF0000' }} className="rounded-md flex items-center justify-center text-white" >
          <svg viewBox="0 0 24 24" fill="white" className="w-2/3 h-2/3"><polygon points="9,7 17,12 9,17"/></svg>
        </div>,
  };
  return styles[id] || null;
}

// ============== Tab 1: Engagement Overview ==============
function EngagementOverview() {
  const totalReach = window.SOCIAL_PLATFORMS.reduce((s, p) => s + p.reach, 0);
  const totalFollowers = window.SOCIAL_PLATFORMS.reduce((s, p) => s + p.followers, 0);
  const totalPosts = window.SOCIAL_PLATFORMS.reduce((s, p) => s + p.posts, 0);
  const avgEng = (window.SOCIAL_PLATFORMS.reduce((s, p) => s + p.eng, 0) / window.SOCIAL_PLATFORMS.length).toFixed(1);

  return (
    <div className="space-y-5">
      {/* Hero KPIs */}
      <div className="grid grid-cols-12 gap-4">
        <Card className="col-span-12 lg:col-span-8 bg-gradient-to-br from-fuchsia-50 via-white to-orange-50 border-pink-100" pad={false}>
          <div className="p-5 grid grid-cols-4 gap-4">
            <KpiTile icon="users" label="Total Followers" value={(totalFollowers/1000).toFixed(1) + 'K'}      trend={6.4} color="#E1306C" />
            <KpiTile icon="bolt"  label="Reach 30d"       value={(totalReach/1000).toFixed(0) + 'K'}        trend={18.2} color="#7C3AED" />
            <KpiTile icon="spark" label="Engagement avg"  value={avgEng + '%'}                              trend={2.1} color="#10B981" />
            <KpiTile icon="chart" label="Posts 30d"       value={totalPosts}                                trend={12} color="#2F5DE5" />
          </div>
        </Card>

        {/* Sparkline overall */}
        <Card className="col-span-12 lg:col-span-4" title="Reach trend · 30 days">
          <ReachSparkline />
          <div className="text-[11px] text-ink-500 mt-2">เทรนด์เพิ่มขึ้นต่อเนื่อง · พีค TikTok วันที่ 14</div>
        </Card>
      </div>

      {/* Platform grid */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
        {window.SOCIAL_PLATFORMS.map(p => <PlatformCard key={p.id} platform={p} />)}
      </div>
    </div>
  );
}

function KpiTile({ icon, label, value, trend, color }) {
  return (
    <div>
      <div className="flex items-center gap-2 text-[11px] text-ink-500 mb-1.5">
        <div className="w-6 h-6 rounded-md flex items-center justify-center" style={{ background: color + '20', color }}>
          <Icon name={icon} className="w-3 h-3" />
        </div>
        <span>{label}</span>
      </div>
      <div className="text-2xl font-semibold num text-ink-900">{value}</div>
      <div className={`text-[11px] font-medium num ${trend > 0 ? 'text-emerald-600' : 'text-rose-500'}`}>
        {trend > 0 ? '▲' : '▼'} {Math.abs(trend)}% wow
      </div>
    </div>
  );
}

function PlatformCard({ platform: p }) {
  // Synthesize sparkline data deterministically
  const seed = p.id.charCodeAt(0) + p.id.charCodeAt(1);
  const data = Array.from({ length: 14 }, (_, i) => Math.sin((i + seed) * 0.5) * 30 + 60 + i * (p.growth / 4));
  const w = 200, h = 50;
  const min = Math.min(...data), max = Math.max(...data);
  const xS = (i) => (i / (data.length - 1)) * w;
  const yS = (v) => h - ((v - min) / (max - min)) * h;
  const path = data.map((v, i) => (i === 0 ? `M ${xS(i)} ${yS(v)}` : `L ${xS(i)} ${yS(v)}`)).join(' ');

  return (
    <Card pad={false} className={!p.connected ? 'opacity-70' : ''}>
      <div className="p-4">
        <div className="flex items-center gap-2.5 mb-3">
          <PlatformLogo id={p.id} size={36} />
          <div className="flex-1 min-w-0">
            <div className="flex items-center gap-1.5">
              <span className="text-sm font-semibold text-ink-900">{p.label}</span>
              {p.connected
                ? <Pill color="#10B981" tint="#E7F8F1" size="xs" icon={<span className="w-1 h-1 rounded-full bg-emerald-500" />}>connected</Pill>
                : <Pill color="#94A3B8" tint="#F1F5F9" size="xs">not connected</Pill>
              }
            </div>
            <div className="text-[10px] text-ink-400 truncate">{p.user}</div>
          </div>
        </div>

        <div className="grid grid-cols-2 gap-3 mb-2">
          <div>
            <div className="text-[10px] text-ink-400 uppercase tracking-wider">Followers</div>
            <div className="text-base font-semibold num text-ink-900">{p.followers.toLocaleString()}</div>
            <div className={`text-[10px] num font-medium ${p.growth > 0 ? 'text-emerald-600' : 'text-rose-500'}`}>▲ {p.growth}%</div>
          </div>
          <div>
            <div className="text-[10px] text-ink-400 uppercase tracking-wider">Engagement</div>
            <div className="text-base font-semibold num text-ink-900">{p.eng}%</div>
            <div className="text-[10px] text-ink-400 num">reach {(p.reach/1000).toFixed(1)}K</div>
          </div>
        </div>

        <svg viewBox={`0 0 ${w} ${h}`} className="w-full">
          <path d={`${path} L ${w} ${h} L 0 ${h} Z`} fill={p.color + '20'} />
          <path d={path} stroke={p.color} strokeWidth="1.5" fill="none" strokeLinecap="round" />
        </svg>
      </div>
    </Card>
  );
}

function ReachSparkline() {
  const seed = 7;
  const data = Array.from({ length: 30 }, (_, i) => 40 + Math.sin((i + seed) * 0.3) * 15 + i * 1.4);
  const w = 320, h = 100;
  const min = Math.min(...data), max = Math.max(...data);
  const xS = (i) => (i / (data.length - 1)) * w;
  const yS = (v) => h - ((v - min) / (max - min)) * (h - 8);
  const path = data.map((v, i) => (i === 0 ? `M ${xS(i)} ${yS(v)}` : `L ${xS(i)} ${yS(v)}`)).join(' ');
  return (
    <svg viewBox={`0 0 ${w} ${h}`} className="w-full">
      <defs>
        <linearGradient id="grdReach" x1="0" x2="0" y1="0" y2="1">
          <stop offset="0%" stopColor="#7C3AED" stopOpacity="0.32" />
          <stop offset="100%" stopColor="#7C3AED" stopOpacity="0" />
        </linearGradient>
      </defs>
      <path d={`${path} L ${w} ${h} L 0 ${h} Z`} fill="url(#grdReach)" />
      <path d={path} stroke="#7C3AED" strokeWidth="2" fill="none" strokeLinecap="round" />
    </svg>
  );
}

// ============== Tab 2: Trending Content ==============
function TrendingView() {
  return (
    <div className="space-y-5">
      <Card title={
        <div className="flex items-center gap-2">
          <span className="text-sm font-semibold text-ink-800">🔥 Mass Trending Topics</span>
          <span className="text-[11px] text-ink-400">· หัวข้อที่กำลังมา · update รายชั่วโมง</span>
        </div>
      }>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
          {window.TRENDING_TOPICS.map(t => (
            <div key={t.id} className={`relative rounded-xl p-4 border ${t.hot ? 'border-orange-200 bg-gradient-to-br from-orange-50/60 to-white' : 'border-ink-100 bg-white'}`}>
              {t.hot && <div className="absolute top-2 right-2 text-[10px] font-bold text-orange-600">🔥 HOT</div>}
              <div className="flex items-center gap-2 mb-2">
                <span className="text-2xl">{t.emoji}</span>
                <div>
                  <div className="text-sm font-semibold text-ink-900">{t.topic}</div>
                  <div className="text-[10px] text-ink-400">Volume · {t.volume}</div>
                </div>
              </div>
              <div className="text-2xl font-semibold num text-emerald-600 mb-2">▲{t.trend}%</div>
              <div className="flex flex-wrap gap-1 mb-3">
                {t.hashtags.map(h => (
                  <code key={h} className="text-[10px] font-mono text-brand-600 bg-brand-50 px-1.5 py-0.5 rounded">{h}</code>
                ))}
              </div>
              <button className="w-full text-[11px] font-semibold py-1.5 rounded-md bg-ink-900 text-white hover:bg-ink-700 transition-colors">
                สร้าง content จาก topic นี้
              </button>
            </div>
          ))}
        </div>
      </Card>

      {/* Suggested formats */}
      <Card title="💡 รูปแบบ Content ที่ Convert ดีในตอนนี้">
        <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
          {[
            { fmt: 'Reel · POV',         desc: '15-30s · มุมมองที่ 1 + Hook ที่ 3 วินาทีแรก', plat: ['ig','tt'],     conv: 8.4 },
            { fmt: 'Carousel ความรู้',   desc: '5-10 slides · เปิดด้วยปัญหา ปิดด้วย CTA',     plat: ['ig','fb','th'],conv: 6.1 },
            { fmt: 'Thread / Tweet ยาว', desc: 'แชร์เรื่องจริง · 5-7 posts',                  plat: ['th'],          conv: 4.8 },
          ].map((f, i) => (
            <div key={i} className="rounded-xl border border-ink-100 p-4 bg-white">
              <div className="text-sm font-semibold text-ink-900">{f.fmt}</div>
              <div className="text-[11px] text-ink-500 mt-1 leading-relaxed">{f.desc}</div>
              <div className="flex items-center justify-between mt-3 pt-3 border-t border-ink-100">
                <div className="flex gap-1">{f.plat.map(p => <PlatformLogo key={p} id={p} size={20} />)}</div>
                <span className="text-[11px] num font-semibold text-emerald-600">{f.conv}% conv</span>
              </div>
            </div>
          ))}
        </div>
      </Card>
    </div>
  );
}

// ============== Tab 3: Daily Content Planner ==============
function ContentPlanner() {
  const [posts, setPosts] = useState(window.CONTENT_TODAY);

  const summary = {
    posted:    posts.filter(p => p.status === 'posted').length,
    scheduled: posts.filter(p => p.status === 'scheduled').length,
    draft:     posts.filter(p => p.status === 'draft').length,
    idea:      posts.filter(p => p.status === 'idea').length,
  };

  const updateStatus = (id, status) => setPosts(prev => prev.map(p => p.id === id ? { ...p, status } : p));

  return (
    <div className="space-y-5">
      {/* Day strip + summary */}
      <Card pad={false}>
        <div className="px-5 pt-4 pb-3 flex items-center justify-between">
          <div>
            <div className="text-[11px] uppercase tracking-wider text-ink-400 font-semibold">วันนี้</div>
            <div className="text-lg font-semibold text-ink-900">14 พฤศจิกายน 2568 · 5 ต่อวัน</div>
          </div>
          <div className="flex items-center gap-3 text-xs">
            <span className="num"><span className="font-semibold text-emerald-600">{summary.posted}</span> Posted</span>
            <span className="num"><span className="font-semibold text-brand-600">{summary.scheduled}</span> Scheduled</span>
            <span className="num"><span className="font-semibold text-gold-600">{summary.draft}</span> Draft</span>
            <span className="num"><span className="font-semibold text-ink-400">{summary.idea}</span> Idea</span>
          </div>
        </div>
        {/* Progress bar */}
        <div className="px-5 pb-4">
          <div className="flex h-2 rounded-full overflow-hidden bg-ink-100">
            <div style={{ width: `${summary.posted/5*100}%`,    background: '#10B981' }} />
            <div style={{ width: `${summary.scheduled/5*100}%`, background: '#2F5DE5' }} />
            <div style={{ width: `${summary.draft/5*100}%`,     background: '#F59E0B' }} />
          </div>
        </div>
      </Card>

      {/* Posts list */}
      <div className="space-y-3">
        {posts.map(p => <ContentSlot key={p.id} post={p} onStatus={updateStatus} />)}
        <button className="w-full py-3 border border-dashed border-ink-200 rounded-xl text-xs font-medium text-ink-500 hover:bg-ink-50 hover:border-ink-300 transition-colors">
          + เพิ่ม content slot (เกิน 5 ต่อวัน)
        </button>
      </div>
    </div>
  );
}

function ContentSlot({ post, onStatus }) {
  const topic = window.TRENDING_TOPICS.find(t => t.id === post.topic);
  const statusMap = {
    posted:    { label: 'Posted',    color: '#10B981', tint: '#E7F8F1' },
    scheduled: { label: 'Scheduled', color: '#2F5DE5', tint: '#EEF4FF' },
    draft:     { label: 'Draft',     color: '#F59E0B', tint: '#FFF6E0' },
    idea:      { label: 'Idea',      color: '#94A3B8', tint: '#F1F5F9' },
  };
  const st = statusMap[post.status];

  return (
    <Card pad={false}>
      <div className="p-4 flex items-start gap-3">
        {/* Slot number */}
        <div className="w-10 h-10 rounded-lg bg-gradient-to-br from-fuchsia-500 to-orange-500 text-white flex items-center justify-center font-bold flex-shrink-0">
          {post.slot}
        </div>

        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2 mb-1">
            <span className="text-base">{topic.emoji}</span>
            <span className="text-[11px] text-ink-500">{topic.topic}</span>
            <span className="text-ink-300">·</span>
            <span className="text-[11px] num text-ink-500">⏱ {post.time}</span>
            <span className="text-ink-300">·</span>
            <span className="text-[11px] text-ink-500">{post.format}</span>
            <Pill color={st.color} tint={st.tint} size="xs" className="ml-auto">{st.label}</Pill>
          </div>
          <div className="text-sm font-semibold text-ink-900 mb-2">{post.hook}</div>

          {/* Performance (if posted) */}
          {post.perf && (
            <div className="flex items-center gap-3 text-[11px] mb-2">
              <span className="num text-ink-700"><span className="text-emerald-600 font-semibold">▲</span> {post.perf.v.toLocaleString()} views</span>
              <span className="num text-ink-700"><span className="text-pink-500 font-semibold">♡</span> {post.perf.e} engagements</span>
            </div>
          )}

          {/* Platforms + actions */}
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-1.5">
              <span className="text-[10px] text-ink-400 uppercase tracking-wider">post to</span>
              {post.platforms.map(p => <PlatformLogo key={p} id={p} size={20} />)}
            </div>
            <div className="flex items-center gap-1">
              {post.status === 'idea' && <Btn size="sm" variant="ghost" onClick={() => onStatus(post.id, 'draft')}>เริ่มเขียน</Btn>}
              {post.status === 'draft' && <Btn size="sm" variant="ghost" onClick={() => onStatus(post.id, 'scheduled')}>ตั้งเวลา</Btn>}
              {post.status === 'scheduled' && <Btn size="sm" variant="brand" icon={<Icon name="bolt" className="w-3 h-3" />} onClick={() => onStatus(post.id, 'posted')}>โพสต์เลย</Btn>}
              {post.status === 'posted' && <span className="text-[11px] text-emerald-600 font-semibold">✓ โพสต์แล้ว</span>}
            </div>
          </div>
        </div>
      </div>
    </Card>
  );
}

// ============== Tab 4: Auto-post Integrations ==============
function Integrations() {
  return (
    <div className="space-y-5">
      <Card title="Auto-post Connections" action={<Pill color="#10B981" tint="#E7F8F1" icon={<span className="w-1.5 h-1.5 rounded-full bg-emerald-500" />}>{window.SOCIAL_PLATFORMS.filter(p => p.connected).length} / {window.SOCIAL_PLATFORMS.length} connected</Pill>}>
        <div className="space-y-2">
          {window.SOCIAL_PLATFORMS.map(p => (
            <div key={p.id} className="flex items-center gap-3 p-3 rounded-xl border border-ink-100 bg-white">
              <PlatformLogo id={p.id} size={40} />
              <div className="flex-1 min-w-0">
                <div className="text-sm font-semibold text-ink-900">{p.label}</div>
                <div className="text-[11px] text-ink-500 truncate">
                  {p.connected ? <>เชื่อมต่อแล้ว · <span className="text-ink-700">{p.user}</span> · OAuth token valid</> : 'ยังไม่ได้เชื่อมต่อ'}
                </div>
              </div>
              {p.connected ? (
                <div className="flex items-center gap-2">
                  <Pill color="#10B981" tint="#E7F8F1" size="xs" icon={<Icon name="check" className="w-3 h-3" />}>OK</Pill>
                  <Btn variant="ghost" size="sm">Disconnect</Btn>
                </div>
              ) : (
                <Btn variant="brand" size="sm" icon={<Icon name="bolt" className="w-3 h-3" />}>เชื่อมต่อ</Btn>
              )}
            </div>
          ))}
        </div>
      </Card>

      {/* Posting queue */}
      <Card title="Posting Queue · นัดโพสต์อัตโนมัติ">
        <div className="space-y-2">
          {window.CONTENT_TODAY.filter(p => p.status === 'scheduled').map(p => (
            <div key={p.id} className="flex items-center gap-3 p-3 rounded-xl border border-ink-100 bg-white">
              <div className="text-center w-12">
                <div className="text-xs font-semibold num">{p.time}</div>
                <div className="text-[9px] text-ink-400">today</div>
              </div>
              <div className="flex-1 min-w-0">
                <div className="text-xs font-semibold text-ink-900 truncate">{p.hook}</div>
                <div className="text-[10px] text-ink-500">{p.format} · {p.platforms.length} platforms</div>
              </div>
              <div className="flex gap-1">
                {p.platforms.map(plat => <PlatformLogo key={plat} id={plat} size={20} />)}
              </div>
            </div>
          ))}
          {window.CONTENT_TODAY.filter(p => p.status === 'scheduled').length === 0 && (
            <div className="text-center py-8 text-[11px] text-ink-400">ยังไม่มี post ที่ตั้งเวลา</div>
          )}
        </div>
      </Card>

      {/* API workflow */}
      <Card title="API Workflow">
        <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
          {[
            { step: 1, title: 'OAuth Connect',    desc: 'User authorize → backend store refresh_token (encrypted in DB)' },
            { step: 2, title: 'Schedule',         desc: 'Frontend POST /api/social/schedule → Redis queue + cron job' },
            { step: 3, title: 'Auto-publish',     desc: 'Cron picks up jobs → fans out to each platform API → log results' },
          ].map(s => (
            <div key={s.step} className="rounded-xl border border-ink-100 p-4 bg-white">
              <div className="flex items-center gap-2 mb-2">
                <div className="w-6 h-6 rounded-full bg-brand-500 text-white flex items-center justify-center text-xs font-bold">{s.step}</div>
                <span className="text-sm font-semibold text-ink-900">{s.title}</span>
              </div>
              <div className="text-[11px] text-ink-500 leading-relaxed">{s.desc}</div>
            </div>
          ))}
        </div>
      </Card>
    </div>
  );
}

window.SocialView = SocialView;
