/* Dashboard — central screen */

function Sparkline({ data, color = "#1677ff", fill = "rgba(22,119,255,0.15)", height = 48, width = 200 }) {
  const max = Math.max(...data), min = Math.min(...data);
  const r = max - min || 1;
  const pts = data.map((v, i) => [
    (i / (data.length - 1)) * width,
    height - ((v - min) / r) * (height - 6) - 3,
  ]);
  const line = pts.map((p, i) => (i ? "L" : "M") + p[0].toFixed(1) + "," + p[1].toFixed(1)).join(" ");
  const area = line + ` L${width},${height} L0,${height} Z`;
  return (
    <svg viewBox={`0 0 ${width} ${height}`} preserveAspectRatio="none" style={{width:"100%",height,display:"block"}}>
      <path d={area} fill={fill}/>
      <path d={line} stroke={color} strokeWidth="2" fill="none"/>
    </svg>
  );
}

function BarSpark({ data, color = "#faad14", height = 48, width = 200 }) {
  const max = Math.max(...data);
  const w = width / data.length;
  return (
    <svg viewBox={`0 0 ${width} ${height}`} preserveAspectRatio="none" style={{width:"100%",height,display:"block"}}>
      {data.map((v, i) => (
        <rect key={i} x={i * w + w * 0.15} y={height - (v / max) * height * 0.9}
              width={w * 0.7} height={(v / max) * height * 0.9} fill={color} rx="1"/>
      ))}
    </svg>
  );
}

function StatCard({ label, value, trend, trendUp = true, color, kind, data }) {
  const trendCls = !trendUp ? (color === "#faad14" ? "warn" : "dn") : "";
  return (
    <div className="stat-card">
      <div className="body">
        <div className="l">{label}</div>
        <div className="row">
          <div className="v">{value}</div>
          <span className={`trend ${trendCls}`}>
            {trendUp ? "↗" : "↘"} {trend}
          </span>
        </div>
      </div>
      <div className="spark">
        {kind === "bar"
          ? <BarSpark data={data} color={color}/>
          : <Sparkline data={data} color={color}
                       fill={color === "#f5222d" ? "rgba(245,34,45,.15)"
                            : color === "#52c41a" ? "rgba(82,196,26,.18)"
                            : color === "#faad14" ? "rgba(250,173,20,.2)"
                            : "rgba(22,119,255,.15)"}/>}
      </div>
    </div>
  );
}

function WelcomeBanner() {
  return (
    <div className="welcome">
      <div style={{display:"flex",flexDirection:"column",gap:16,padding:"6px"}}>
        <h2>Welcome to TolbNet</h2>
        <p>The purpose of a product update is to add new features, fix bugs or improve the performance of the product.</p>
        <button className="cta">View full statistic</button>
      </div>
      <div className="deco">
        {/* placeholder illustration — Mantis ships a /assets/images/analytics/welcome-banner.png */}
        <svg viewBox="0 0 240 160" fill="none">
          <g opacity=".75">
            <rect x="20" y="20" width="100" height="120" rx="6" fill="#fff" opacity=".15"/>
            <rect x="30" y="40" width="60" height="6" rx="3" fill="#fff" opacity=".5"/>
            <rect x="30" y="52" width="40" height="4" rx="2" fill="#fff" opacity=".3"/>
            <path d="M30 110 L50 80 L70 95 L90 60 L110 75" stroke="#fff" strokeWidth="2" fill="none"/>
          </g>
          <g opacity=".9" transform="translate(130,30)">
            <circle cx="40" cy="40" r="32" fill="#fff" opacity=".18"/>
            <circle cx="40" cy="40" r="20" fill="#fff" opacity=".28"/>
          </g>
          <path d="M180 110 q 30 -30 50 0" stroke="#fff" strokeWidth="3" fill="none" opacity=".55" strokeLinecap="round"/>
          <path d="M225 105 L230 110 L225 115" stroke="#fff" strokeWidth="3" fill="none" opacity=".55" strokeLinecap="round" strokeLinejoin="round"/>
        </svg>
      </div>
    </div>
  );
}

function OrdersTable() {
  const rows = [
    { id: "#84564564", category: "Camera Lens", price: "$40,570", qty: 423, status: "Rejected", st: "error" },
    { id: "#84564786", category: "Laptop",      price: "$180,139", qty: 65,  status: "Approved", st: "success" },
    { id: "#84564987", category: "Mobile",      price: "$90,989", qty: 320, status: "Rejected", st: "error" },
    { id: "#84564111", category: "Handset",     price: "$10,239", qty: 86,  status: "Pending",  st: "pending" },
    { id: "#84564002", category: "Computer Acc.",price: "$56,439",qty: 215, status: "Approved", st: "success" },
  ];
  return (
    <table className="tbl">
      <thead><tr>
        <th>Tracking No.</th><th>Product Name</th><th style={{textAlign:"right"}}>Total Order</th><th>Status</th><th style={{textAlign:"right"}}>Total Amount</th>
      </tr></thead>
      <tbody>
        {rows.map(r => (
          <tr key={r.id}>
            <td className="o-id">{r.id}</td>
            <td style={{color:"#262626"}}>{r.category}</td>
            <td style={{textAlign:"right"}}>{r.qty}</td>
            <td><Tag type={r.st} dot>{r.status}</Tag></td>
            <td style={{textAlign:"right",color:"#262626",fontWeight:500}}>{r.price}</td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}

function TransactionList() {
  const rows = [
    { name:"Payment from #002434", time:"Today, 2:00 AM", amount:"+ $1.430", pct:"35%", up:true,  bg:"#f6ffed", color:"#389e0d", icon:<Icon.Check size={16}/> },
    { name:"Payment from #002434", time:"Today, 6:00 AM", amount:"- $1.430", pct:"35%", up:false, bg:"#fff1f0", color:"#cf1322", icon:<Icon.X size={16}/> },
    { name:"Pending from #002435", time:"Today, 2:00 AM", amount:"- $2.430", pct:"35%", up:false, bg:"#fffbe6", color:"#d48806", icon:<Icon.Help size={16}/> },
  ];
  return (
    <div>
      {rows.map((r, i) => (
        <div className="tx-row" key={i}>
          <div className="av" style={{background:r.bg,color:r.color}}>{r.icon}</div>
          <div className="body">
            <div className="t">{r.name}</div>
            <div className="m">{r.time}</div>
          </div>
          <div className={`amount ${r.up ? "up" : "dn"}`}>
            {r.amount}<span className="pct">{r.pct}</span>
          </div>
        </div>
      ))}
    </div>
  );
}

function PageViewsTable() {
  const rows = [
    { page:"Admin Home",     path:"/demo/admin/index.html",      n:"31.74%" },
    { page:"Form Elements",  path:"/demo/admin/forms.html",      n:"28.53%" },
    { page:"Utilities",      path:"/demo/admin/util.html",       n:"25.35%" },
    { page:"Form Validation",path:"/demo/admin/validation.html", n:"23.17%" },
    { page:"Modals",         path:"/demo/admin/modals.html",     n:"22.21%" },
  ];
  return (
    <div>
      {rows.map((r, i) => (
        <div key={i} style={{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 0",borderBottom:i<rows.length-1?"1px solid #f0f0f0":""}}>
          <div>
            <div style={{font:"500 14px/22px var(--font-sans)",color:"#262626"}}>{r.page}</div>
            <div style={{font:"400 12px/20px var(--font-sans)",color:"#8c8c8c"}}>{r.path}</div>
          </div>
          <Tag type="blue">{r.n}</Tag>
        </div>
      ))}
    </div>
  );
}

function IncomeChart() {
  const w = 660, h = 240, pad = 28;
  const data = [62,11,32,12,11,42,12,22,12];
  const max = 80;
  const xstep = (w - pad * 2) / (data.length - 1);
  const pts = data.map((v,i) => [pad + i*xstep, h - pad - (v/max)*(h - pad*2)]);
  const line = pts.map((p,i)=>(i?"L":"M")+p[0]+","+p[1]).join(" ");
  const area = line + ` L${w-pad},${h-pad} L${pad},${h-pad} Z`;
  return (
    <svg viewBox={`0 0 ${w} ${h}`} style={{width:"100%",height:240,display:"block"}}>
      {/* gridlines */}
      {[0,1,2,3,4].map(i => {
        const y = pad + i * (h - pad*2) / 4;
        return <line key={i} x1={pad} y1={y} x2={w-pad} y2={y} stroke="#f0f0f0" strokeWidth="1"/>
      })}
      {[0,1,2,3,4].map(i => (
        <text key={i} x="2" y={pad + i*(h-pad*2)/4 + 4} fill="#8c8c8c" fontSize="10">{80 - i*20}</text>
      ))}
      <defs>
        <linearGradient id="ar" x1="0" x2="0" y1="0" y2="1">
          <stop offset="0%" stopColor="#1677ff" stopOpacity=".25"/>
          <stop offset="100%" stopColor="#1677ff" stopOpacity="0"/>
        </linearGradient>
      </defs>
      <path d={area} fill="url(#ar)"/>
      <path d={line} stroke="#1677ff" strokeWidth="2" fill="none"/>
      {pts.map((p,i) => <circle key={i} cx={p[0]} cy={p[1]} r="3" fill="#1677ff"/>)}
      {data.map((_,i) => (
        <text key={i} x={pad+i*xstep} y={h-8} fill="#8c8c8c" fontSize="10" textAnchor="middle">Jan {i+1}</text>
      ))}
    </svg>
  );
}

function Dashboard() {
  return (
    <>
      <div className="crumbs">
        <a>Home</a><span className="sep">/</span>
        <a>Dashboard</a><span className="sep">/</span>
        <span className="cur">Analytics</span>
      </div>
      <h1 className="page-title">Analytics</h1>

      <WelcomeBanner/>

      <div className="section-label" style={{font:"600 20px/28px var(--font-sans)",margin:"24px 0 12px"}}>Analytic Overview</div>
      <div className="grid-4">
        <StatCard label="Total Users"     value="78,250"  trend="70.5%" trendUp color="#1677ff" data={[12,18,14,20,22,30,28,35,32,40]}/>
        <StatCard label="Total Order"     value="18,800"  trend="27.4%" trendUp={false} color="#f5222d" data={[40,38,36,34,30,28,30,26,28,24]}/>
        <StatCard label="Total Sales"     value="$35,078" trend="27.4%" trendUp={false} color="#faad14" kind="bar" data={[18,30,22,38,28,42,30,46,32,40,36,44,28,40,30,36]}/>
        <StatCard label="Total Marketing" value="$1,12,083" trend="70.5%" trendUp color="#52c41a" data={[10,14,12,18,16,22,18,24,22,28,26,32]}/>
      </div>

      <div className="grid-2-3">
        <div>
          <div style={{font:"600 16px/24px var(--font-sans)",margin:"4px 0 14px"}}>Income Overview</div>
          <Card>
          <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:10,fontSize:12,color:"#8c8c8c"}}>
            <span><span style={{color:"#f5222d"}}>▼</span> Compare to: 01 Dec 2021 – 08 Jan 2022</span>
            <div style={{display:"flex",gap:8,alignItems:"center"}}>
              <div className="seg" style={{display:"inline-flex",background:"#f5f5f5",borderRadius:4,padding:2}}>
                <span style={{padding:"3px 12px",borderRadius:3,background:"#fff",color:"#262626",fontSize:12,fontWeight:500}}>Week</span>
                <span style={{padding:"3px 12px",color:"#595959",fontSize:12}}>Month</span>
              </div>
              <Button type="default" size="sm">By Total Volume ▾</Button>
            </div>
          </div>
          <IncomeChart/>
          </Card>
        </div>

        <div>
          <div style={{font:"600 16px/24px var(--font-sans)",margin:"4px 0 14px"}}>Page Views by Page Title</div>
          <Card><PageViewsTable/></Card>
        </div>

        <div>
          <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",margin:"4px 0 14px"}}>
            <div style={{font:"600 16px/24px var(--font-sans)"}}>Recent Orders</div>
            <span style={{color:"#8c8c8c",letterSpacing:2,cursor:"pointer"}}>···</span>
          </div>
          <Card padding={false}><OrdersTable/></Card>
        </div>

        <div>
          <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",margin:"4px 0 14px"}}>
            <div style={{font:"600 16px/24px var(--font-sans)"}}>Transaction History</div>
            <span style={{color:"#8c8c8c",letterSpacing:2,cursor:"pointer"}}>···</span>
          </div>
          <Card><TransactionList/></Card>
        </div>
      </div>
    </>
  );
}

window.Dashboard = Dashboard;
