import { z } from "zod";
import type { TargetingSpec } from "../types/meta-api.js";

const baseStyles = `
  * { margin: 0; padding: 0; box-sizing: border-box; }
  body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; background: #1a1a2e; color: #eee; padding: 20px; }
  .container { max-width: 1000px; margin: 0 auto; }
  h1 { font-size: 28px; margin-bottom: 24px; color: #fff; }
  .section { background: #16213e; border-radius: 12px; padding: 24px; margin-bottom: 20px; box-shadow: 0 4px 12px rgba(0,0,0,0.3); }
  .section h2 { font-size: 18px; color: #e94560; margin-bottom: 16px; display: flex; align-items: center; gap: 8px; }
  .age-range-container { margin: 20px 0; }
  .age-scale { position: relative; height: 60px; background: linear-gradient(90deg, #0f3460 0%, #e94560 50%, #0f3460 100%); border-radius: 8px; margin: 16px 0; }
  .age-range-highlight { position: absolute; top: 0; height: 100%; background: #e94560; border-radius: 8px; opacity: 0.8; }
  .age-labels { display: flex; justify-content: space-between; font-size: 12px; color: #999; margin-top: 8px; }
  .gender-split { display: flex; gap: 16px; margin: 16px 0; }
  .gender-card { flex: 1; background: #0f3460; border-radius: 8px; padding: 16px; text-align: center; }
  .gender-card h3 { font-size: 14px; color: #e94560; margin-bottom: 8px; }
  .gender-percentage { font-size: 24px; font-weight: 700; color: #fff; }
  .tags { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 12px; }
  .tag { display: inline-block; background: #0f3460; color: #fff; padding: 6px 14px; border-radius: 20px; font-size: 12px; border: 1px solid #e94560; }
  .location-list { background: #0f3460; border-radius: 8px; padding: 16px; margin-top: 12px; }
  .location-item { padding: 8px 0; border-bottom: 1px solid #16213e; color: #ddd; }
  .location-item:last-child { border-bottom: none; }
  .reach-gauge { position: relative; height: 120px; margin: 24px 0; }
  .gauge-bg { position: absolute; width: 100%; height: 20px; top: 50%; transform: translateY(-50%); background: linear-gradient(90deg, #27ae60, #f39c12, #e74c3c); border-radius: 10px; }
  .gauge-marker { position: absolute; top: 30%; width: 4px; height: 60px; background: #fff; box-shadow: 0 2px 8px rgba(255,255,255,0.5); }
  .gauge-labels { display: flex; justify-content: space-between; margin-top: 70px; font-size: 12px; color: #999; }
  .reach-value { text-align: center; font-size: 28px; font-weight: 700; color: #e94560; margin-top: 16px; }
  .reach-label { text-align: center; font-size: 14px; color: #999; }
  .error { background: #16213e; padding: 40px; border-radius: 12px; text-align: center; color: #e94560; }
`;

export function register(server: any, client: any): void {
  server.tool(
    "audience_builder",
    "Audience Builder - Visualize targeting spec with demographics, interests, and estimated reach",
    {
      account_id: z.string().describe("Ad Account ID (format: act_XXXXX)"),
      targeting_spec: z.string().describe("Targeting specification as JSON string")
    },
    async (params: { account_id: string; targeting_spec: string }) => {
      try {
        // Parse targeting spec
        const targeting: TargetingSpec = JSON.parse(params.targeting_spec);

        // Get reach estimate from Meta API
        let reachEstimate: any = null;
        try {
          const reachResponse = await client.get(
            `/${params.account_id}/reachestimate`,
            {
              targeting_spec: params.targeting_spec
            }
          ) as any;
          reachEstimate = reachResponse.data?.[0] || reachEstimate;
        } catch (e) {
          // Reach estimate might fail, that's okay
          console.error("Could not fetch reach estimate:", e);
        }

        // Extract data
        const ageMin = targeting.age_min || 18;
        const ageMax = targeting.age_max || 65;
        const ageRangePercent = ((ageMin - 18) / (65 - 18)) * 100;
        const ageRangeWidth = ((ageMax - ageMin) / (65 - 18)) * 100;

        const genders = targeting.genders || [1, 2];
        const hasMale = genders.includes(1);
        const hasFemale = genders.includes(2);
        const genderAll = hasMale && hasFemale;
        const malePercent = genderAll ? 50 : hasMale ? 100 : 0;
        const femalePercent = genderAll ? 50 : hasFemale ? 100 : 0;

        const countries = targeting.geo_locations?.countries || [];
        const regions = targeting.geo_locations?.regions || [];
        const cities = targeting.geo_locations?.cities || [];

        const interests = targeting.interests || [];
        const behaviors = targeting.behaviors || [];
        const customAudiences = targeting.custom_audiences || [];

        const estimatedLower = reachEstimate?.users_lower_bound || 0;
        const estimatedUpper = reachEstimate?.users_upper_bound || 0;
        const estimatedMid = estimatedLower > 0 ? (estimatedLower + estimatedUpper) / 2 : 0;

        // Gauge marker position (0-100%)
        const maxReach = 10000000; // 10M as max for visualization
        const gaugePosition = estimatedMid > 0 ? Math.min((estimatedMid / maxReach) * 100, 100) : 50;

        // Build HTML
        const html = `<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Audience Builder</title>
  <style>${baseStyles}</style>
</head>
<body>
  <div class="container">
    <h1>👥 Audience Builder</h1>
    
    ${countries.length > 0 || regions.length > 0 || cities.length > 0 ? `
    <div class="section">
      <h2>🌍 Locations</h2>
      <div class="location-list">
        ${countries.map(c => `<div class="location-item">📍 ${c}</div>`).join('')}
        ${regions.map((r: any) => `<div class="location-item">📍 ${r.key || r.name || 'Region'}</div>`).join('')}
        ${cities.map((c: any) => `<div class="location-item">📍 ${c.key || c.name || 'City'}</div>`).join('')}
        ${countries.length === 0 && regions.length === 0 && cities.length === 0 ? '<div class="location-item">No specific locations targeted</div>' : ''}
      </div>
    </div>
    ` : ''}
    
    <div class="section">
      <h2>🎂 Age Range</h2>
      <div class="age-range-container">
        <div class="age-scale">
          <div class="age-range-highlight" style="left: ${ageRangePercent}%; width: ${ageRangeWidth}%;"></div>
        </div>
        <div class="age-labels">
          <span>18</span>
          <span>25</span>
          <span>35</span>
          <span>45</span>
          <span>55</span>
          <span>65+</span>
        </div>
        <div style="text-align: center; margin-top: 12px; color: #e94560; font-weight: 600;">
          Ages ${ageMin} - ${ageMax}
        </div>
      </div>
    </div>
    
    <div class="section">
      <h2>⚧️ Gender Split</h2>
      <div class="gender-split">
        <div class="gender-card">
          <h3>Male</h3>
          <div class="gender-percentage">${malePercent}%</div>
        </div>
        <div class="gender-card">
          <h3>Female</h3>
          <div class="gender-percentage">${femalePercent}%</div>
        </div>
      </div>
    </div>
    
    ${interests.length > 0 ? `
    <div class="section">
      <h2>💡 Interests</h2>
      <div class="tags">
        ${interests.map(i => `<span class="tag">${i.name || i.id}</span>`).join('')}
      </div>
    </div>
    ` : ''}
    
    ${behaviors.length > 0 ? `
    <div class="section">
      <h2>🎯 Behaviors</h2>
      <div class="tags">
        ${behaviors.map(b => `<span class="tag">${b.name || b.id}</span>`).join('')}
      </div>
    </div>
    ` : ''}
    
    ${customAudiences.length > 0 ? `
    <div class="section">
      <h2>📋 Custom Audiences</h2>
      <div class="tags">
        ${customAudiences.map(ca => `<span class="tag">${ca.name || ca.id}</span>`).join('')}
      </div>
    </div>
    ` : ''}
    
    <div class="section">
      <h2>📊 Estimated Reach</h2>
      <div class="reach-gauge">
        <div class="gauge-bg"></div>
        <div class="gauge-marker" style="left: ${gaugePosition}%;"></div>
        <div class="gauge-labels">
          <span>0</span>
          <span>2.5M</span>
          <span>5M</span>
          <span>7.5M</span>
          <span>10M+</span>
        </div>
      </div>
      ${estimatedMid > 0 ? `
      <div class="reach-value">${estimatedMid.toLocaleString()}</div>
      <div class="reach-label">Potential Reach (mid-point)</div>
      ${estimatedLower > 0 && estimatedUpper > 0 ? `
      <div class="reach-label" style="margin-top: 8px;">
        Range: ${estimatedLower.toLocaleString()} - ${estimatedUpper.toLocaleString()}
      </div>
      ` : ''}
      ` : `
      <div class="reach-label">Reach estimate unavailable</div>
      `}
    </div>
  </div>
</body>
</html>`;

        const textSummary = `Audience Builder\n\n` +
          `Age Range: ${ageMin} - ${ageMax}\n` +
          `Gender: ${genderAll ? 'All' : hasMale ? 'Male' : 'Female'}\n` +
          `Locations: ${countries.length} countries, ${regions.length} regions, ${cities.length} cities\n` +
          `Interests: ${interests.length}\n` +
          `Behaviors: ${behaviors.length}\n` +
          `Custom Audiences: ${customAudiences.length}\n` +
          `${estimatedMid > 0 ? `Estimated Reach: ${estimatedMid.toLocaleString()} (${estimatedLower.toLocaleString()} - ${estimatedUpper.toLocaleString()})` : 'Reach estimate unavailable'}`;

        return {
          structuredContent: {
            type: "resource",
            resource: {
              uri: "meta-ads://app/audience-builder",
              mimeType: "text/html",
              text: html
            }
          },
          content: [{ type: "text", text: textSummary }]
        };
      } catch (error: any) {
        const errorHtml = `<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><title>Error</title><style>${baseStyles}</style></head>
<body><div class="container"><div class="error"><h2>⚠️ Error Building Audience</h2><p>${error.message}</p></div></div></body>
</html>`;
        
        return {
          structuredContent: {
            type: "resource",
            resource: { uri: "meta-ads://app/audience-builder", mimeType: "text/html", text: errorHtml }
          },
          content: [{ type: "text", text: `Error: ${error.message}` }]
        };
      }
    },
    { title: "👥 Audience Builder", readOnlyHint: true }
  );
}
