"use client";

import { useEffect, useRef, useState } from "react";
import "./north-star.css";
import { OppCharts } from "@/components/partner-charts";
import { CapabilityIcon } from "@/components/capability-icons";
import {
  CAPABILITIES,
  COMPARISON,
  FLYWHEELS,
  INDUSTRIES,
  INDUSTRY_TABS,
  JOURNEY,
  NORTHSTAR_NODES,
  OPPORTUNITY_CARDS,
  SYSTEM_TABS,
  type Flywheel as FlywheelData,
} from "@/lib/north-star";
import type { NorthStarContent, SectionCopy } from "@/lib/north-star-content";

function nodeIcon(id: string) {
  switch (id) {
    case "growth":
      return <path d="M22 12h-4l-3 9L9 3l-3 9H2" />;
    case "customer":
      return <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2M9 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8Z" />;
    case "operations":
      return <path d="M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6ZM19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-2.82 1.17V21a2 2 0 1 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.6 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.6a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 2.82 1.17l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9Z" />;
    default:
      return <><rect x="4" y="4" width="16" height="16" rx="2" /><path d="M9 9h6M9 13h6M9 17h4" /></>;
  }
}

function FlywheelSvg({ data, idx }: { data: FlywheelData; idx: number }) {
  const size = 220;
  const c = 110;
  const r = 92;
  const n = data.steps.length;
  return (
    <svg className="flywheel-svg" width={size} height={size} viewBox={`0 0 ${size} ${size}`}>
      <defs>
        <linearGradient id={`pfw${idx}`} x1="0" y1="0" x2={size} y2={size}>
          <stop offset="0" stopColor="#2fb46a" />
          <stop offset="0.5" stopColor="#2bbac8" />
          <stop offset="1" stopColor="#5aa8f0" />
        </linearGradient>
      </defs>
      <circle cx={c} cy={c} r={r} fill="none" stroke="rgba(47,180,106,0.16)" strokeWidth="1" />
      <circle cx={c} cy={c} r={r - 30} fill="none" stroke="rgba(47,180,106,0.1)" strokeWidth="1" />
      <g>
        <path
          d={`M ${c} ${c - r} A ${r} ${r} 0 0 1 ${c + r} ${c}`}
          fill="none"
          stroke={`url(#pfw${idx})`}
          strokeWidth="2.5"
          strokeLinecap="round"
        />
        <animateTransform
          attributeName="transform"
          type="rotate"
          from={`0 ${c} ${c}`}
          to={`360 ${c} ${c}`}
          dur={`${20 + idx * 2}s`}
          repeatCount="indefinite"
        />
      </g>
      {data.steps.map((step, i) => {
        const a = (i / n) * 2 * Math.PI - Math.PI / 2;
        const x = c + Math.cos(a) * (r + 6);
        const y = c + Math.sin(a) * (r + 6);
        const anchor = Math.abs(Math.cos(a)) < 0.3 ? "middle" : x > c ? "end" : "start";
        return (
          <text key={step} x={x} y={y} textAnchor={anchor} dominantBaseline="middle" fill="#3a4a42" fontSize="9" fontFamily="var(--font-body)" fontWeight="600">
            {step}
          </text>
        );
      })}
      <circle cx={c} cy={c} r="24" fill="rgba(79,196,107,0.12)" stroke="rgba(79,196,107,0.3)" strokeWidth="1" />
      <text x={c} y={c} textAnchor="middle" dominantBaseline="middle" fill="#36b85f" fontSize="8" fontFamily="var(--font-display)" fontWeight="700">
        {data.title.split(" ")[0].toUpperCase()}
      </text>
    </svg>
  );
}

const NODE_POS: Record<string, React.CSSProperties> = {
  growth: { top: "2%", left: "50%", transform: "translateX(-50%)" },
  customer: { top: "50%", right: "0%", transform: "translateY(-50%)" },
  operations: { bottom: "2%", left: "50%", transform: "translateX(-50%)" },
  technology: { top: "50%", left: "0%", transform: "translateY(-50%)" },
};

/** Renders a section header (eyebrow + heading with optional gradient em + subtitle). */
function SectionHead({
  copy,
  headingClass,
  subClass,
  subStyle,
  reveal = true,
}: {
  copy: SectionCopy;
  headingClass: string;
  subClass?: string;
  subStyle?: React.CSSProperties;
  reveal?: boolean;
}) {
  const r = reveal ? " reveal" : "";
  return (
    <>
      <p className={`eyebrow${r}`}>{copy.eyebrow}</p>
      <h2 className={`${headingClass}${r}`} style={{ whiteSpace: "pre-line" }}>
        {copy.heading}
        {copy.headingEm ? <em>{copy.headingEm}</em> : null}
        {copy.headingSuffix}
        {copy.heading2 ? (
          <>
            {"\n"}
            <em>{copy.heading2}</em>
          </>
        ) : null}
      </h2>
      {copy.sub ? (
        <p className={`${subClass ?? "section-sub"}${r}`} style={subStyle}>
          {copy.sub}
        </p>
      ) : null}
    </>
  );
}

export function NorthStarPage({ content }: { content: NorthStarContent }) {
  const rootRef = useRef<HTMLDivElement>(null);
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const [activeSystem, setActiveSystem] = useState<string>(SYSTEM_TABS[0].id);
  const [activeIndustry, setActiveIndustry] = useState<string>(INDUSTRY_TABS[0].id);
  const [filled, setFilled] = useState(false);

  // Reveal + imagine via IntersectionObserver
  useEffect(() => {
    const root = rootRef.current;
    if (!root) return;
    const els = root.querySelectorAll(".reveal, .imagine-line");
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            e.target.classList.add(e.target.classList.contains("imagine-line") ? "visible" : "in");
          } else if (e.target.classList.contains("imagine-line")) {
            e.target.classList.remove("visible");
          }
        });
      },
      { threshold: 0.15 },
    );
    els.forEach((el) => io.observe(el));
    const t = setTimeout(() => setFilled(true), 300);
    return () => {
      io.disconnect();
      clearTimeout(t);
    };
  }, []);

  // Particle field
  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext("2d");
    if (!ctx) return;
    let raf = 0;
    const resize = () => {
      canvas.width = canvas.offsetWidth;
      canvas.height = canvas.offsetHeight;
    };
    resize();
    window.addEventListener("resize", resize);
    const COUNT = 60;
    const ps = Array.from({ length: COUNT }, (_, i) => ({
      x: ((i * 97) % 100) / 100,
      y: ((i * 53) % 100) / 100,
      vx: (((i * 31) % 100) / 100 - 0.5) * 0.0006,
      vy: (((i * 17) % 100) / 100 - 0.5) * 0.0006,
      r: 0.5 + ((i * 7) % 15) / 10,
      a: 0.05 + ((i * 13) % 25) / 100,
    }));
    const draw = () => {
      const w = canvas.width;
      const h = canvas.height;
      ctx.clearRect(0, 0, w, h);
      ps.forEach((p) => {
        p.x += p.vx;
        p.y += p.vy;
        if (p.x < 0 || p.x > 1) p.vx *= -1;
        if (p.y < 0 || p.y > 1) p.vy *= -1;
        ctx.beginPath();
        ctx.arc(p.x * w, p.y * h, p.r, 0, Math.PI * 2);
        ctx.fillStyle = `rgba(43,186,200,${p.a + 0.12})`;
        ctx.fill();
      });
      for (let i = 0; i < ps.length; i++) {
        for (let j = i + 1; j < ps.length; j++) {
          const dx = (ps[i].x - ps[j].x) * w;
          const dy = (ps[i].y - ps[j].y) * h;
          const dist = Math.hypot(dx, dy);
          if (dist < 150) {
            ctx.beginPath();
            ctx.moveTo(ps[i].x * w, ps[i].y * h);
            ctx.lineTo(ps[j].x * w, ps[j].y * h);
            ctx.strokeStyle = `rgba(54,184,95,${0.08 * (1 - dist / 150)})`;
            ctx.lineWidth = 0.5;
            ctx.stroke();
          }
        }
      }
      raf = requestAnimationFrame(draw);
    };
    draw();
    return () => {
      cancelAnimationFrame(raf);
      window.removeEventListener("resize", resize);
    };
  }, []);

  return (
    <div className="partner" ref={rootRef}>
      {/* HERO */}
      <section id="hero">
        <div className="orb orb-1" />
        <div className="orb orb-2" />
        <canvas id="particles-canvas" ref={canvasRef} />

        <svg className="hero-northstar" viewBox="0 0 500 500" fill="none">
          <g>
            <circle cx="250" cy="250" r="80" stroke="rgba(47,180,106,0.18)" strokeWidth="1" />
            <circle cx="250" cy="250" r="140" stroke="rgba(47,180,106,0.1)" strokeWidth="1" />
            <circle cx="250" cy="250" r="200" stroke="rgba(47,180,106,0.06)" strokeWidth="1" />
            <polygon points="250,170 258,242 330,250 258,258 250,330 242,258 170,250 242,242" fill="rgba(47,180,106,0.14)" />
            <animateTransform attributeName="transform" type="rotate" from="0 250 250" to="360 250 250" dur="60s" repeatCount="indefinite" />
          </g>
        </svg>

        <div style={{ position: "relative", zIndex: 2 }}>
          <p className="eyebrow reveal" style={{ marginBottom: 24 }}>
            {content.hero.eyebrow}
          </p>
          <h1 className="hero-headline reveal" style={{ whiteSpace: "pre-line" }}>
            {content.hero.heading}
            {content.hero.headingEm ? <em>{content.hero.headingEm}</em> : null}
            {content.hero.headingSuffix}
            {content.hero.heading2 ? (
              <>
                {"\n"}
                <em>{content.hero.heading2}</em>
              </>
            ) : null}
          </h1>
          <p className="hero-sub reveal">{content.hero.sub}</p>
          <div className="hero-cta-group reveal">
            <a
              href="https://calendly.com/wedigtech"
              target="_blank"
              rel="noopener noreferrer"
              className="btn-primary"
            >
              <span>{content.heroPrimaryCta}</span>
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <path d="M5 12h14M12 5l7 7-7 7" />
              </svg>
            </a>
            <a href="#opportunity" className="btn-ghost">
              {content.heroSecondaryCta}
            </a>
          </div>
        </div>
      </section>

      {/* OPPORTUNITY */}
      <section id="opportunity">
        <div className="section-inner">
          <div className="reveal">
            <SectionHead copy={content.opportunity} headingClass="section-heading" reveal={false} />
          </div>

          <div className="opp-grid">
            {OPPORTUNITY_CARDS.map((card) => (
              <div key={card.title} className="opp-card glass-card reveal">
                <h3>{card.title}</h3>
                <p>{card.desc}</p>
                <div className="opp-meter">
                  <div className="opp-meter-fill" style={{ width: filled ? `${card.meter}%` : "0%" }} />
                </div>
                <span style={{ fontSize: 11, color: "var(--text-muted)", marginTop: 8, display: "block" }}>
                  {card.meterLabel}
                </span>
              </div>
            ))}
          </div>

          <OppCharts />
        </div>
      </section>

      {/* NORTHSTAR MAP */}
      <section id="northstar-map">
        <div className="section-inner" style={{ textAlign: "center" }}>
          <SectionHead copy={content.northstar} headingClass="section-heading" subStyle={{ margin: "0 auto" }} />

          <div className="orbital-container reveal">
            <div className="orbit-ring orbit-ring-1 spin" />
            <div className="orbit-ring orbit-ring-2 spin-rev" />
            <div className="orbit-ring orbit-ring-3 spin" />

            <div className="orbital-center pulse-glow">
              <div className="orbital-center-star">✦</div>
              <div className="orbital-center-label">Northstar</div>
            </div>

            {NORTHSTAR_NODES.map((node) => (
              <div key={node.id} className="orbit-node float-anim" style={NODE_POS[node.id]}>
                <div className="orbit-node-dot">
                  <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#2bbac8" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
                    {nodeIcon(node.id)}
                  </svg>
                </div>
                <div className="orbit-node-label">{node.label}</div>
                <div className="orbit-tooltip">
                  <h4>{node.title}</h4>
                  <p>{node.desc}</p>
                </div>
              </div>
            ))}

            <svg style={{ position: "absolute", top: 0, left: 0, width: "100%", height: "100%", pointerEvents: "none", zIndex: 5 }} viewBox="0 0 100 100">
              <polygon points="50,8 92,50 50,92 8,50" fill="none" stroke="rgba(47,180,106,0.1)" strokeWidth="0.3" />
            </svg>
          </div>
        </div>
      </section>

      {/* CAPABILITIES */}
      <section id="systems">
        <div className="section-inner">
          <SectionHead copy={content.capabilities} headingClass="section-heading" subStyle={{ marginBottom: 40 }} />

          <div className="system-tabs reveal">
            {SYSTEM_TABS.map((t) => (
              <button
                key={t.id}
                className={`system-tab${activeSystem === t.id ? " active" : ""}`}
                onClick={() => setActiveSystem(t.id)}
              >
                {t.label}
              </button>
            ))}
          </div>

          {SYSTEM_TABS.map((t) => (
            <div key={t.id} style={{ display: activeSystem === t.id ? "block" : "none" }}>
              <div className="capabilities-grid">
                {CAPABILITIES[t.id].map((cap) => (
                  <div key={cap.title} className="capability-card glass-card">
                    <CapabilityIcon title={cap.title} className="cap-icon" />
                    <h4>{cap.title}</h4>
                    <p>{cap.desc}</p>
                  </div>
                ))}
              </div>
            </div>
          ))}
        </div>
      </section>

      {/* FLYWHEELS */}
      <section id="flywheels">
        <div className="section-inner">
          <div style={{ textAlign: "center" }} className="reveal">
            <SectionHead copy={content.flywheels} headingClass="section-heading" subStyle={{ margin: "0 auto" }} reveal={false} />
          </div>

          <div className="flywheel-grid">
            {FLYWHEELS.map((fw, idx) => (
              <div key={fw.title} className="flywheel-card glass-card reveal">
                <FlywheelSvg data={fw} idx={idx} />
                <h3>{fw.title}</h3>
                <p>{fw.desc}</p>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* JOURNEY */}
      <section id="journey">
        <div className="section-inner">
          <div style={{ textAlign: "center" }} className="reveal">
            <SectionHead copy={content.journey} headingClass="section-heading" reveal={false} />
          </div>

          <div className="journey-track">
            {JOURNEY.map((step) => (
              <div key={step.num} className="journey-step glass-card reveal">
                <div className="step-num">{step.num}</div>
                <h3>{step.title}</h3>
                <div className="step-detail">{step.detail}</div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* INDUSTRIES */}
      <section id="industries">
        <div className="section-inner">
          <div className="reveal">
            <SectionHead copy={content.industries} headingClass="section-heading" subStyle={{ marginBottom: 40 }} reveal={false} />
          </div>

          <div className="ind-tabs reveal">
            {INDUSTRY_TABS.map((t) => (
              <button
                key={t.id}
                className={`ind-tab${activeIndustry === t.id ? " active" : ""}`}
                onClick={() => setActiveIndustry(t.id)}
              >
                {t.label}
              </button>
            ))}
          </div>

          {INDUSTRY_TABS.map((t) => {
            const c = INDUSTRIES[t.id];
            return (
              <div key={t.id} style={{ display: activeIndustry === t.id ? "block" : "none" }}>
                <div className="ind-content">
                  {([
                    ["Common Challenges", c.challenges],
                    ["Hidden Opportunities", c.opportunities],
                    ["Future Possibilities", c.possibilities],
                  ] as const).map(([heading, items]) => (
                    <div key={heading} className="ind-col glass-card">
                      <h4>{heading}</h4>
                      <ul>
                        {items.map((item) => (
                          <li key={item}>{item}</li>
                        ))}
                      </ul>
                    </div>
                  ))}
                </div>
              </div>
            );
          })}
        </div>
      </section>

      {/* COMPARISON */}
      <section id="comparison">
        <div className="section-inner">
          <div style={{ textAlign: "center" }} className="reveal">
            <SectionHead copy={content.comparison} headingClass="section-heading" reveal={false} />
          </div>

          <div className="comp-grid reveal">
            <div className="comp-col vendor">
              <h3>{COMPARISON.vendor.title}</h3>
              {COMPARISON.vendor.rows.map((row) => (
                <div key={row} className="comp-row">
                  <div className="comp-indicator" />
                  <span>{row}</span>
                </div>
              ))}
            </div>
            <div className="comp-col partner-col">
              <h3>{COMPARISON.partner.title}</h3>
              {COMPARISON.partner.rows.map((row) => (
                <div key={row} className="comp-row">
                  <div className="comp-indicator" />
                  <span>{row}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </section>

      {/* IMAGINE */}
      <section id="imagine">
        <div className="section-inner" style={{ padding: "80px 0" }}>
          <div className="orb" style={{ width: 500, height: 500, background: "radial-gradient(circle,rgba(47,180,106,0.15),transparent 70%)", top: "30%", left: "50%", transform: "translateX(-50%)" }} />
          <p className="eyebrow reveal" style={{ marginBottom: 64 }}>
            {content.imagineEyebrow}
          </p>
          <div className="imagine-line">
            Imagine if your leadership team could see opportunities{" "}
            <em>before competitors.</em>
          </div>
          <div className="imagine-line">
            Imagine if customer needs became visible{" "}
            <em>before they were expressed.</em>
          </div>
          <div className="imagine-line">
            Imagine if every decision was supported by{" "}
            <em>intelligence, not instinct alone.</em>
          </div>
          <div className="imagine-line">
            Imagine if your operations could handle{" "}
            <em>ten times the volume without ten times the team.</em>
          </div>
          <div className="imagine-line">
            Imagine if growth was no longer limited by the cost of{" "}
            <em>scale.</em>
          </div>
        </div>
      </section>

      {/* FINAL CTA */}
      <section id="final-cta">
        <div className="cta-orb" />
        <svg style={{ position: "absolute", top: "50%", left: "50%", transform: "translate(-50%,-50%)", width: 400, height: 400, opacity: 0.55, pointerEvents: "none" }} viewBox="0 0 400 400">
          <g>
            <circle cx="200" cy="200" r="60" stroke="rgba(43,186,200,0.45)" strokeWidth="1" fill="none" />
            <circle cx="200" cy="200" r="120" stroke="rgba(43,186,200,0.28)" strokeWidth="1" fill="none" />
            <circle cx="200" cy="200" r="180" stroke="rgba(43,186,200,0.16)" strokeWidth="1" fill="none" />
            <polygon points="200,140 208,192 260,200 208,208 200,260 192,208 140,200 192,192" fill="rgba(43,186,200,0.18)" />
            <animateTransform attributeName="transform" type="rotate" from="0 200 200" to="360 200 200" dur="60s" repeatCount="indefinite" />
          </g>
        </svg>

        <div style={{ position: "relative", zIndex: 2 }}>
          <p className="eyebrow reveal">{content.finalCta.eyebrow}</p>
          <h2 className="final-heading reveal" style={{ whiteSpace: "pre-line" }}>
            {content.finalCta.heading}
            {content.finalCta.headingEm ? <em>{content.finalCta.headingEm}</em> : null}
            {content.finalCta.headingSuffix}
            {content.finalCta.heading2 ? (
              <>
                {"\n"}
                <em>{content.finalCta.heading2}</em>
              </>
            ) : null}
          </h2>
          <p className="final-sub reveal">{content.finalCta.sub}</p>
          <div className="final-cta-group reveal">
            <a
              href="https://calendly.com/wedigtech"
              target="_blank"
              rel="noopener noreferrer"
              className="btn-primary"
            >
              <span>{content.finalPrimaryCta}</span>
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <path d="M5 12h14M12 5l7 7-7 7" />
              </svg>
            </a>
            <a href="mailto:partner@wedigtech.com" className="btn-ghost">
              <span>{content.finalSecondaryCta}</span>
            </a>
          </div>
        </div>
      </section>
    </div>
  );
}
