/* SiliconPop — Profile Page */

const ProfilePage = ({ appData, sessionToken, setSessionToken, refreshAppData, setToast }) => {
  const { TopBar, PageShell, SPCard, SPBadge, SPButton, SPTabs, SectionHead, StatCard } = window;
  const [tab, setTab] = React.useState('overview');
  const [identifier, setIdentifier] = React.useState("nicole@siliconpop.demo");
  const [password, setPassword] = React.useState("demo123456");
  const loggedIn = Boolean(sessionToken && appData?.profile?.user);
  const user = appData?.profile?.user;
  const dashboard = appData?.profile?.dashboard || {};

  const stats = dashboard.stats?.length ? [
    { label: '持有授权', value: String((dashboard.licenses || []).length), accent: '#00D4FF' },
    { label: '参与任务', value: String((dashboard.tasks || []).length), accent: '#A78BFA' },
    { label: '收藏 IP', value: String((dashboard.favorites || []).length), accent: '#10B981' },
    { label: '待处理提案', value: String((dashboard.proposals || []).length), accent: '#F59E0B' },
  ] : [
    { label: '持有授权', value: '3', accent: '#00D4FF' },
    { label: '创作内容', value: '27', accent: '#A78BFA' },
    { label: '累计收益', value: '¥8,420', accent: '#10B981' },
    { label: 'Token 余额', value: '12,400', accent: '#F59E0B' },
  ];

  const licenses = dashboard.licenses?.length ? dashboard.licenses.map((item, index) => ({
    ip: item.name,
    type: item.rights,
    expires: item.billing || "长期",
    status: item.status,
    grad: ['linear-gradient(135deg,#6366F1,#00D4FF)','linear-gradient(135deg,#EC4899,#F97316)','linear-gradient(135deg,#10B981,#06B6D4)'][index % 3]
  })) : [
    { ip: 'Luna Nova', type: '音乐+社交授权', expires: '2026-12-31', status: '生效中', grad: 'linear-gradient(135deg,#6366F1,#00D4FF)' },
    { ip: 'Kai Zero', type: '游戏内容授权', expires: '2026-09-15', status: '生效中', grad: 'linear-gradient(135deg,#EC4899,#F97316)' },
    { ip: 'Mira Soft', type: '陪伴场景授权', expires: '2026-06-30', status: '即将到期', grad: 'linear-gradient(135deg,#10B981,#06B6D4)' },
  ];

  const orders = dashboard.licenses?.length ? dashboard.licenses.map((item) => ({
    title: item.name,
    amount: item.payment || "待确认",
    date: item.createdAt ? item.createdAt.slice(0, 10) : "刚刚",
    status: item.status
  })) : [
    { title: '算力 Token 包 · 专业版', amount: '¥299', date: '2026-05-20', status: '已完成' },
    { title: 'Luna Nova 月度授权续费', amount: '¥2,980', date: '2026-05-01', status: '已完成' },
    { title: 'AI 短视频 Agent 订阅', amount: '¥199/月', date: '2026-04-15', status: '自动续费中' },
  ];

  const favorites = dashboard.favorites?.length ? dashboard.favorites.map((item, index) => ({
    name: item.title,
    type: item.kind,
    grad: ['linear-gradient(135deg,#8B5CF6,#EC4899)','linear-gradient(135deg,#06B6D4,#3B82F6)','linear-gradient(135deg,#F472B6,#FBBF24)'][index % 3]
  })) : [
    { name: 'Aria Lin', type: '国风虚拟人', grad: 'linear-gradient(135deg,#8B5CF6,#EC4899)' },
    { name: 'Echo Wave', type: '电子音乐人', grad: 'linear-gradient(135deg,#06B6D4,#3B82F6)' },
    { name: 'Pixel Fox', type: '像素游戏角色', grad: 'linear-gradient(135deg,#F472B6,#FBBF24)' },
  ];

  const handleLogin = async () => {
    try {
      const res = await fetch("/v1/users/login", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ identifier, password })
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "LOGIN_FAILED");
      setSessionToken(data.session_token);
      setToast(`登录成功：${data.user.name}`);
    } catch (err) {
      setToast(`登录失败：${err.message}`);
    }
  };
  const handleRegister = async () => {
    const stamp = Date.now().toString().slice(-6);
    try {
      const res = await fetch("/v1/users/register", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name: `Creator${stamp}`,
          email: `creator${stamp}@siliconpop.demo`,
          phone: `139${stamp.padStart(8, "0")}`,
          password: "demo123456"
        })
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "REGISTER_FAILED");
      setIdentifier(data.email);
      setPassword("demo123456");
      setToast(`注册成功：${data.name}`);
    } catch (err) {
      setToast(`注册失败：${err.message}`);
    }
  };
  const bindWallet = async () => {
    if (!sessionToken) {
      await handleLogin();
      return;
    }
    const res = await fetch("/v1/users/me/bind-wallet", {
      method: "POST",
      headers: { "Content-Type": "application/json", Authorization: `Bearer ${sessionToken}` },
      body: JSON.stringify({ walletAddress: "0x71C4f8B8a7F0d21A8d9f3E2" })
    });
    const data = await res.json();
    if (!res.ok) {
      setToast(`钱包绑定失败：${data.error || "REQUEST_FAILED"}`);
      return;
    }
    setToast("钱包已绑定");
    refreshAppData();
  };
  const createRenewalOrder = async (license) => {
    const res = await fetch("/v1/users/me/orders", {
      method: "POST",
      headers: { "Content-Type": "application/json", Authorization: `Bearer ${sessionToken}` },
      body: JSON.stringify({
        title: `${license.ip} 续费`,
        kind: license.type,
        payment: "支付宝",
        region: "中国内地",
        billing: "月度续费",
        status: "待付款"
      })
    });
    const data = await res.json();
    if (!res.ok) {
      setToast(`续费失败：${data.error || "REQUEST_FAILED"}`);
      return;
    }
    setToast(`续费订单已创建：${license.ip}`);
    refreshAppData();
  };
  const createContract = async (license) => {
    const res = await fetch("/v1/contracts/summary", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        pkg: "default",
        region: "中国内地",
        billing: license.expires || "月度订阅",
        payment: "支付宝",
        entity: user?.name || "Nicole",
        invoiceType: "普通发票",
        contact: user?.email || "nicole@siliconpop.demo",
        persona: "fan"
      })
    });
    const data = await res.json();
    if (!res.ok) {
      setToast(`合同生成失败：${data.error || "REQUEST_FAILED"}`);
      return;
    }
    setToast(`合同摘要已生成：${data.data.templateName}`);
  };

  if (!loggedIn) {
    return (
      <PageShell>
        <TopBar title="我的" />
        <div className="sp-login-hero">
          <div className="sp-login-icon">
            <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="url(#loginGrad)" strokeWidth="1.5" strokeLinecap="round">
              <defs><linearGradient id="loginGrad" x1="0" y1="0" x2="1" y2="1"><stop offset="0%" stopColor="#00D4FF" /><stop offset="100%" stopColor="#6366F1" /></linearGradient></defs>
              <path d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
            </svg>
          </div>
          <h2>登录 SiliconPop</h2>
          <p>登录后可管理授权、查看收益、参与社区任务</p>
          <div className="sp-login-form">
            <input className="sp-input" placeholder="手机号或邮箱" value={identifier} onChange={(event) => setIdentifier(event.target.value)} />
            <input className="sp-input" type="password" placeholder="密码" value={password} onChange={(event) => setPassword(event.target.value)} />
            <SPButton variant="primary" className="sp-full-btn" onClick={handleLogin}>登录</SPButton>
            <SPButton variant="ghost" className="sp-full-btn" onClick={handleRegister}>注册新账户</SPButton>
          </div>
          <div className="sp-login-divider"><span>或</span></div>
          <SPButton variant="ghost" className="sp-full-btn sp-wallet-btn" onClick={bindWallet}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M21 12V7H5a2 2 0 010-4h14v4M3 5v14a2 2 0 002 2h16v-5M18 14a1 1 0 100 2 1 1 0 000-2z" /></svg>
            连接钱包登录
          </SPButton>
        </div>
      </PageShell>
    );
  }

  return (
    <PageShell>
      <TopBar title="我的" rightAction={
        <button className="sp-icon-btn" onClick={bindWallet}>
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"><path d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.066 2.573c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.573 1.066c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.066-2.573c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" /><circle cx="12" cy="12" r="3" /></svg>
        </button>
      } />

      {/* Profile Header */}
      <SPCard className="sp-profile-header">
        <div className="sp-profile-top">
          <div className="sp-profile-avatar" style={{background: 'linear-gradient(135deg,#6366F1,#EC4899)'}}>N</div>
          <div className="sp-profile-info">
            <h2>{user?.name || "Nicole"}</h2>
            <span className="sp-profile-email">{user?.email || "nicole@siliconpop.demo"}</span>
            <div className="sp-profile-badges">
              <SPBadge variant="glow">{user?.profile?.level || "创作者"}</SPBadge>
              <SPBadge variant="subtle">{user?.walletAddress ? "钱包已绑定" : "待绑定钱包"}</SPBadge>
            </div>
          </div>
        </div>
        <div className="sp-profile-wallet">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M21 12V7H5a2 2 0 010-4h14v4M3 5v14a2 2 0 002 2h16v-5M18 14a1 1 0 100 2 1 1 0 000-2z" /></svg>
          <span>{user?.walletAddress || "未绑定钱包"}</span>
        </div>
      </SPCard>

      {/* Stats */}
      <div className="sp-profile-stats">
        {stats.map((s, i) => <StatCard key={i} {...s} />)}
      </div>

      <SPTabs tabs={[
        { id: 'overview', label: '概览' },
        { id: 'licenses', label: '授权' },
        { id: 'orders', label: '订单' },
        { id: 'favorites', label: '收藏' },
      ]} active={tab} onChange={setTab} />

      {/* Overview */}
      {tab === 'overview' && (
        <>
          <SectionHead title="我的授权" actionLabel="管理 →" />
          {licenses.map((l, i) => (
            <SPCard key={i} className="sp-license-card">
              <div className="sp-license-left">
                <div className="sp-license-dot" style={{background: l.grad}}>{l.ip[0]}</div>
                <div>
                  <strong>{l.ip}</strong>
                  <span className="sp-license-type">{l.type}</span>
                </div>
              </div>
              <div className="sp-license-right">
                <SPBadge variant={l.status === '即将到期' ? 'warning' : 'success'}>{l.status}</SPBadge>
                <span className="sp-license-exp">到期 {l.expires}</span>
              </div>
            </SPCard>
          ))}

          <SectionHead title="最近动态" />
          <div className="sp-activity-list">
            {(dashboard.activities || [
              '生成了 Luna Nova 文案内容 v3',
              '参加了「春日二创征集」任务',
              '续费了 Kai Zero 游戏授权',
            ]).map((text, i) => {
              const a = typeof text === "string" ? { text, time: i === 0 ? "刚刚" : `${i + 1}天前`, icon: "✦" } : text;
              return (
              <div key={i} className="sp-activity-item">
                <span className="sp-activity-icon">{a.icon}</span>
                <div className="sp-activity-body">
                  <span>{a.text}</span>
                  <span className="sp-activity-time">{a.time}</span>
                </div>
              </div>
              );
            })}
          </div>
        </>
      )}

      {/* Licenses */}
      {tab === 'licenses' && (
        <div className="sp-licenses-full">
          {licenses.map((l, i) => (
            <SPCard key={i} className="sp-license-full-card">
              <div className="sp-license-full-top">
                <div className="sp-license-dot lg" style={{background: l.grad}}>{l.ip[0]}</div>
                <div>
                  <strong className="sp-license-full-name">{l.ip}</strong>
                  <span className="sp-license-type">{l.type}</span>
                </div>
                <SPBadge variant={l.status === '即将到期' ? 'warning' : 'success'}>{l.status}</SPBadge>
              </div>
              <div className="sp-license-full-meta">
                <div><span>到期时间</span><strong>{l.expires}</strong></div>
                <div><span>使用配额</span><strong>剩余 78%</strong></div>
                <div><span>创作数量</span><strong>{[12, 8, 7][i]}</strong></div>
              </div>
              <div className="sp-license-actions">
                <SPButton variant="sm-ghost" onClick={() => createRenewalOrder(l)}>续费</SPButton>
                <SPButton variant="sm-ghost" onClick={() => createContract(l)}>查看合同</SPButton>
              </div>
            </SPCard>
          ))}
        </div>
      )}

      {/* Orders */}
      {tab === 'orders' && (
        <div className="sp-orders-list">
          {orders.map((o, i) => (
            <SPCard key={i} className="sp-order-card">
              <div className="sp-order-top">
                <strong>{o.title}</strong>
                <SPBadge variant={o.status === '自动续费中' ? 'glow' : 'subtle'}>{o.status}</SPBadge>
              </div>
              <div className="sp-order-meta">
                <span>{o.date}</span>
                <span className="sp-order-amount">{o.amount}</span>
              </div>
            </SPCard>
          ))}
        </div>
      )}

      {/* Favorites */}
      {tab === 'favorites' && (
        <div className="sp-favorites-grid">
          {favorites.map((f, i) => (
            <SPCard key={i} className="sp-fav-card">
              <div className="sp-fav-thumb" style={{background: f.grad}}>
                <span>{f.name[0]}</span>
              </div>
              <strong>{f.name}</strong>
              <span className="sp-fav-type">{f.type}</span>
            </SPCard>
          ))}
        </div>
      )}

      {/* Logout */}
      <SPButton variant="ghost" className="sp-full-btn sp-logout-btn" onClick={() => { setSessionToken(""); refreshAppData(); }}>退出登录</SPButton>
    </PageShell>
  );
};

Object.assign(window, { ProfilePage });
