<!DOCTYPE html>
<html lang="en">
<head>
  <title><%= title %></title>
  <%- include('partials/head') %>
</head>
<body class="bg-surface font-body text-on-surface">
<%- include('partials/sidebar') %>
<%- include('partials/flash') %>

<div class="ml-64 min-h-screen flex flex-col">
  <%- include('partials/topbar') %>

  <main class="flex-1">
    <div class="p-10 max-w-7xl mx-auto space-y-10">

      <!-- Header & Period Picker -->
      <div class="flex justify-between items-end">
        <div>
          <h2 class="text-3xl font-extrabold font-headline text-on-surface tracking-tight">Business Insights</h2>
          <p class="text-on-surface-variant mt-1">Reviewing performance for the last <%= period %> days.</p>
        </div>
        <div class="flex items-center space-x-2 bg-surface-container-lowest p-2 rounded-xl shadow-sm">
          <a href="/analytics?period=7" class="px-4 py-2 text-sm font-<%= period === '7' ? 'bold bg-primary text-white rounded-lg shadow-md shadow-primary/20' : 'medium text-on-surface-variant hover:text-primary' %> transition-colors">7D</a>
          <a href="/analytics?period=30" class="px-4 py-2 text-sm font-<%= period === '30' ? 'bold bg-primary text-white rounded-lg shadow-md shadow-primary/20' : 'medium text-on-surface-variant hover:text-primary' %> transition-colors">30D</a>
          <a href="/analytics?period=90" class="px-4 py-2 text-sm font-<%= period === '90' ? 'bold bg-primary text-white rounded-lg shadow-md shadow-primary/20' : 'medium text-on-surface-variant hover:text-primary' %> transition-colors">90D</a>
          <div class="w-px h-6 bg-outline-variant/30"></div>
          <button class="flex items-center space-x-2 px-4 py-2 text-sm font-medium text-on-surface hover:bg-surface-container transition-colors rounded-lg">
            <span class="material-symbols-outlined text-lg">calendar_today</span>
            <span>Custom</span>
          </button>
        </div>
      </div>

      <!-- KPI Grid -->
      <div class="grid grid-cols-1 md:grid-cols-4 gap-6">
        <div class="bg-surface-container-lowest p-6 rounded-xl shadow-sm border border-outline-variant/10 group hover:shadow-md transition-shadow">
          <div class="flex justify-between items-start mb-4">
            <div class="p-2 bg-emerald-50 rounded-lg"><span class="material-symbols-outlined text-emerald-700">payments</span></div>
            <div class="flex items-center text-emerald-600 text-xs font-bold bg-emerald-50 px-2 py-1 rounded">
              <span class="material-symbols-outlined text-xs mr-1">trending_up</span>+12.5%
            </div>
          </div>
          <p class="text-xs font-bold text-on-surface-variant uppercase tracking-widest">Total Sales</p>
          <h3 class="text-2xl font-extrabold font-headline mt-1">$<%= parseFloat(kpis.total_sales || 0).toLocaleString('en-US', {minimumFractionDigits:2, maximumFractionDigits:2}) %></h3>
          <!-- Mini sparkline -->
          <div class="mt-4 h-12 w-full flex items-end space-x-1">
            <% const sparks = [4,6,10,7,12,9,5]; sparks.forEach(function(h, i) { %>
            <div class="w-full bg-emerald-<%= i===4?'400':'100' %> rounded-t-sm group-hover:bg-emerald-<%= i===4?'500':'200' %> transition-colors" style="height:<%=h*4%>px"></div>
            <% }) %>
          </div>
        </div>
        <div class="bg-surface-container-lowest p-6 rounded-xl shadow-sm border border-outline-variant/10 group hover:shadow-md transition-shadow">
          <div class="flex justify-between items-start mb-4">
            <div class="p-2 bg-blue-50 rounded-lg"><span class="material-symbols-outlined text-blue-700">ads_click</span></div>
            <div class="flex items-center text-emerald-600 text-xs font-bold bg-emerald-50 px-2 py-1 rounded">
              <span class="material-symbols-outlined text-xs mr-1">trending_up</span>+3.2%
            </div>
          </div>
          <p class="text-xs font-bold text-on-surface-variant uppercase tracking-widest">Conversion Rate</p>
          <h3 class="text-2xl font-extrabold font-headline mt-1"><%= (parseFloat(kpis.conversion_rate || 0) * 100).toFixed(2) %>%</h3>
          <div class="mt-4 h-12 w-full flex items-end space-x-1">
            <% [8,5,9,6,10,11,8].forEach(function(h,i) { %>
            <div class="w-full bg-blue-<%= i===5?'400':'100' %> rounded-t-sm group-hover:bg-blue-<%= i===5?'500':'200' %> transition-colors" style="height:<%=h*4%>px"></div>
            <% }) %>
          </div>
        </div>
        <div class="bg-surface-container-lowest p-6 rounded-xl shadow-sm border border-outline-variant/10 group hover:shadow-md transition-shadow">
          <div class="flex justify-between items-start mb-4">
            <div class="p-2 bg-purple-50 rounded-lg"><span class="material-symbols-outlined text-purple-700">groups</span></div>
            <div class="flex items-center text-red-600 text-xs font-bold bg-red-50 px-2 py-1 rounded">
              <span class="material-symbols-outlined text-xs mr-1">trending_down</span>-0.8%
            </div>
          </div>
          <p class="text-xs font-bold text-on-surface-variant uppercase tracking-widest">Sessions</p>
          <h3 class="text-2xl font-extrabold font-headline mt-1"><%= (parseInt(kpis.total_sessions || 0)).toLocaleString() %></h3>
          <div class="mt-4 h-12 w-full flex items-end space-x-1">
            <% [10,12,9,8,7,6,5].forEach(function(h,i) { %>
            <div class="w-full bg-purple-<%= i===1?'400':'100' %> rounded-t-sm group-hover:bg-purple-<%= i===1?'500':'200' %> transition-colors" style="height:<%=h*4%>px"></div>
            <% }) %>
          </div>
        </div>
        <div class="bg-surface-container-lowest p-6 rounded-xl shadow-sm border border-outline-variant/10 group hover:shadow-md transition-shadow">
          <div class="flex justify-between items-start mb-4">
            <div class="p-2 bg-orange-50 rounded-lg"><span class="material-symbols-outlined text-orange-700">shopping_basket</span></div>
            <div class="flex items-center text-emerald-600 text-xs font-bold bg-emerald-50 px-2 py-1 rounded">
              <span class="material-symbols-outlined text-xs mr-1">trending_up</span>+5.4%
            </div>
          </div>
          <p class="text-xs font-bold text-on-surface-variant uppercase tracking-widest">Avg Order Value</p>
          <h3 class="text-2xl font-extrabold font-headline mt-1">$<%= parseFloat(kpis.avg_order_value || 0).toFixed(2) %></h3>
          <div class="mt-4 h-12 w-full flex items-end space-x-1">
            <% [5,7,6,9,12,10,8].forEach(function(h,i) { %>
            <div class="w-full bg-orange-<%= i===4?'400':'100' %> rounded-t-sm group-hover:bg-orange-<%= i===4?'500':'200' %> transition-colors" style="height:<%=h*4%>px"></div>
            <% }) %>
          </div>
        </div>
      </div>

      <!-- Charts Section -->
      <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
        <!-- Sales Over Time -->
        <div class="lg:col-span-2 bg-surface-container-lowest p-8 rounded-xl shadow-sm border border-outline-variant/10">
          <div class="flex justify-between items-center mb-8">
            <div>
              <h4 class="text-xl font-bold font-headline">Sales Performance</h4>
              <p class="text-sm text-on-surface-variant">Daily gross volume tracking</p>
            </div>
            <div class="flex space-x-2">
              <button class="p-2 hover:bg-surface-container rounded-lg transition-colors">
                <span class="material-symbols-outlined text-on-surface-variant">download</span>
              </button>
            </div>
          </div>
          <!-- SVG Line Chart -->
          <div class="h-64 relative mt-4">
            <svg class="w-full h-full" viewBox="0 0 1000 280" preserveAspectRatio="none">
              <line stroke="#edf4ff" stroke-width="1" x1="0" x2="1000" y1="60" y2="60"/>
              <line stroke="#edf4ff" stroke-width="1" x1="0" x2="1000" y1="140" y2="140"/>
              <line stroke="#edf4ff" stroke-width="1" x1="0" x2="1000" y1="220" y2="220"/>
              <defs>
                <linearGradient id="cg" x1="0" x2="0" y1="0" y2="1">
                  <stop offset="0%" stop-color="#00654b" stop-opacity="0.12"/>
                  <stop offset="100%" stop-color="#00654b" stop-opacity="0"/>
                </linearGradient>
              </defs>
              <% if (chartData && chartData.length > 1) {
                const maxSales = Math.max(...chartData.map(d => parseFloat(d.total_sales)));
                const points = chartData.map((d, i) => {
                  const x = Math.round((i / (chartData.length-1)) * 1000);
                  const y = Math.round(250 - (parseFloat(d.total_sales) / maxSales) * 200);
                  return `${x},${y}`;
                }).join(' ');
                const lastPoint = chartData[chartData.length-1];
                const lastX = 1000, lastY = Math.round(250-(parseFloat(lastPoint.total_sales)/maxSales)*200);
              %>
              <path d="M<%= chartData.map((d,i)=>`${Math.round(i/(chartData.length-1)*1000)},${Math.round(250-(parseFloat(d.total_sales)/Math.max(...chartData.map(x=>parseFloat(x.total_sales))))*200)}`).join(' L') %> L1000,280 L0,280 Z" fill="url(#cg)"/>
              <path d="M<%= chartData.map((d,i)=>`${Math.round(i/(chartData.length-1)*1000)},${Math.round(250-(parseFloat(d.total_sales)/Math.max(...chartData.map(x=>parseFloat(x.total_sales))))*200)}`).join(' L') %>" fill="none" stroke="#00654b" stroke-width="4" stroke-linecap="round"/>
              <% } else { %>
              <path d="M0,200 Q200,120 400,180 T700,100 T1000,60 L1000,280 L0,280 Z" fill="url(#cg)"/>
              <path d="M0,200 Q200,120 400,180 T700,100 T1000,60" fill="none" stroke="#00654b" stroke-width="4" stroke-linecap="round"/>
              <% } %>
            </svg>
          </div>
          <div class="flex justify-between mt-2 text-xs font-bold text-on-surface-variant uppercase tracking-tighter">
            <% if (chartData && chartData.length > 0) {
              const step = Math.max(1, Math.floor(chartData.length / 6));
              for (let i = 0; i < chartData.length; i += step) {
                const d = new Date(chartData[i].date);
            %>
            <span><%= d.toLocaleDateString('en-US',{month:'short',day:'numeric'}) %></span>
            <% }} else { %>
            <span>No data</span>
            <% } %>
          </div>
        </div>

        <!-- Live View -->
        <div class="bg-surface-container-high/50 backdrop-blur-md p-8 rounded-xl shadow-sm border border-outline-variant/20 relative overflow-hidden flex flex-col">
          <div class="relative z-10 flex flex-col h-full">
            <div class="flex justify-between items-start mb-6">
              <div>
                <h4 class="text-xl font-bold font-headline">Live View</h4>
                <div class="flex items-center space-x-2 mt-1">
                  <span class="flex h-2 w-2 relative">
                    <span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-75"></span>
                    <span class="relative inline-flex rounded-full h-2 w-2 bg-emerald-500"></span>
                  </span>
                  <p class="text-sm text-emerald-800 font-medium">Real-time Activity</p>
                </div>
              </div>
              <span class="material-symbols-outlined text-on-surface-variant">sensors</span>
            </div>
            <div class="flex-1 flex flex-col justify-center text-center">
              <span class="text-6xl font-extrabold font-headline text-emerald-900"><%= Math.floor(Math.random()*80+10) %></span>
              <p class="text-on-surface-variant font-medium mt-2">Active visitors now</p>
            </div>
            <div class="mt-6 space-y-4">
              <div class="flex items-center justify-between text-sm">
                <span class="text-on-surface-variant">Active checkouts</span>
                <span class="font-bold text-emerald-800"><%= Math.floor(Math.random()*20+5) %></span>
              </div>
              <div class="w-full bg-emerald-900/10 h-1.5 rounded-full">
                <div class="bg-emerald-600 h-full rounded-full" style="width:28%"></div>
              </div>
              <div class="flex items-center justify-between text-sm">
                <span class="text-on-surface-variant">In cart</span>
                <span class="font-bold text-emerald-800"><%= Math.floor(Math.random()*40+10) %></span>
              </div>
              <div class="w-full bg-emerald-900/10 h-1.5 rounded-full">
                <div class="bg-emerald-600 h-full rounded-full" style="width:57%"></div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Bottom Section -->
      <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
        <!-- Top Products -->
        <div class="bg-surface-container-lowest p-8 rounded-xl shadow-sm border border-outline-variant/10">
          <h4 class="text-xl font-bold font-headline mb-8">Top Products</h4>
          <div class="space-y-6">
            <% if (topProducts.length === 0) { %>
            <p class="text-sm text-on-surface-variant text-center py-8">No product sales data for this period.</p>
            <% } %>
            <% const maxRevenue = topProducts.length > 0 ? Math.max(...topProducts.map(p=>parseFloat(p.revenue))) : 1; %>
            <% topProducts.forEach(function(p, i) { %>
            <div class="group cursor-pointer">
              <div class="flex justify-between text-sm mb-2">
                <span class="font-semibold group-hover:text-primary transition-colors"><%= p.title %></span>
                <span class="text-on-surface-variant">$<%= parseFloat(p.revenue).toFixed(2) %></span>
              </div>
              <div class="w-full bg-surface-container h-3 rounded-full overflow-hidden">
                <div class="bg-primary h-full rounded-full transition-all group-hover:scale-x-105 origin-left duration-500"
                  style="width:<%= Math.round((parseFloat(p.revenue)/maxRevenue)*100) %>%;opacity:<%=1-(i*0.15)%>"></div>
              </div>
            </div>
            <% }) %>
          </div>
        </div>

        <!-- Recent High-Value Orders -->
        <div class="bg-surface-container-lowest p-8 rounded-xl shadow-sm border border-outline-variant/10">
          <div class="flex justify-between items-center mb-8">
            <h4 class="text-xl font-bold font-headline">Recent High-Value Orders</h4>
            <a href="/orders" class="text-primary text-sm font-bold hover:underline">View All</a>
          </div>
          <div class="space-y-4">
            <% if (recentOrders.length === 0) { %>
            <p class="text-sm text-on-surface-variant text-center py-8">No orders in this period.</p>
            <% } %>
            <% recentOrders.forEach(function(o) { %>
            <div class="p-4 rounded-xl hover:bg-surface-container-low transition-colors flex items-center justify-between">
              <div class="flex items-center space-x-4">
                <div class="w-10 h-10 bg-surface-container-high rounded-full flex items-center justify-center font-bold text-emerald-900 text-sm">
                  <%= (o.customer_name||'U').split(' ').map(n=>n[0]).join('').substring(0,2).toUpperCase() %>
                </div>
                <div>
                  <p class="font-bold text-sm"><%= o.customer_name || 'Unknown' %></p>
                  <p class="text-xs text-on-surface-variant"><%= new Date(o.created_at).toLocaleDateString() %> • <%= o.order_number %></p>
                </div>
              </div>
              <div class="text-right">
                <p class="font-bold text-sm">$<%= parseFloat(o.total).toFixed(2) %></p>
                <% if (o.payment_status === 'paid') { %>
                <span class="px-2 py-0.5 bg-emerald-100 text-emerald-800 text-[10px] font-bold uppercase rounded">Paid</span>
                <% } else { %>
                <span class="px-2 py-0.5 bg-secondary-container text-on-secondary-container text-[10px] font-bold uppercase rounded"><%= o.payment_status %></span>
                <% } %>
              </div>
            </div>
            <% }) %>
          </div>
        </div>
      </div>

    </div>
  </main>
</div>
</body>
</html>
