const SKILLS = [
  { id: "workflow", label: "Workflow Automation", items: ["Zapier", "Make.com", "GoHighLevel", "n8n", "Webhooks", "Triggers", "Conditional Logic", "Error Handling"], level: 95 },
  { id: "api", label: "API Integration", items: ["REST APIs", "Webhooks", "Custom Triggers", "Multi-step Logic", "OAuth", "JSON Parsing", "HTTP Requests", "Authentication"], level: 88 },
  { id: "crm", label: "CRM & Marketing", items: ["GoHighLevel", "Marketing Automation", "Lead Management", "Campaign Workflows", "Pipeline Stages", "Contact Tagging", "Email Sequences", "SMS Campaigns"], level: 92 },
  { id: "data", label: "Data Management", items: ["Google Sheets", "Airtable", "Data Pipelines", "Reporting", "CSV Processing", "Database Sync", "Data Transformation", "Scheduled Reports"], level: 85 },
  { id: "ai", label: "AI Automation", items: ["AI Workflows", "Process Automation", "Intelligent Routing", "Smart Triggers", "OpenAI", "RAG Pipelines", "VAPI", "Vector Stores"], level: 90 },
  { id: "webdesign", label: "Web Design", items: ["Websites", "Landing Pages", "Dashboards", "Responsive UI", "Claude Code", "Codex", "HyperFrames", "Brand Systems"], level: 89 },
  { id: "funnels", label: "Funnels", items: ["Booking Pages", "Thank You Pages", "Sales Funnels", "Lead Capture", "GoHighLevel Pages", "Conversion Optimization", "CTA Flow", "Form Strategy"], level: 87 },
];

const PLATFORMS = [
  { name: "GoHighLevel" }, { name: "n8n" }, { name: "Make.com" }, { name: "Zapier" },
  { name: "OpenAI" }, { name: "VAPI" }, { name: "Supabase" }, { name: "Airtable" },
  { name: "Google Sheets" }, { name: "Facebook API" }, { name: "Google Gemini" }, { name: "Gmail API" },
];

const ArcGauge = ({ level, size = 138 }) => {
  const radius = 50;
  const cx = size / 2;
  const cy = size / 2;
  const circumference = 2 * Math.PI * radius;
  const filled = (level / 100) * circumference;

  return (
    <div style={{ position: "relative", width: size, height: size, flexShrink: 0 }}>
      <svg
        width={size}
        height={size}
        viewBox={`0 0 ${size} ${size}`}
        style={{ transform: "rotate(-90deg)", position: "absolute", inset: 0 }}
      >
        <circle cx={cx} cy={cy} r={radius} fill="none" stroke="rgba(255,255,255,0.05)" strokeWidth={7} />
        <circle
          cx={cx}
          cy={cy}
          r={radius}
          fill="none"
          stroke="var(--teal)"
          strokeWidth={7}
          strokeLinecap="round"
          strokeDasharray={`${filled} ${circumference}`}
          style={{
            filter: "drop-shadow(0 0 6px rgba(20,184,166,0.85)) drop-shadow(0 0 12px rgba(20,184,166,0.4))",
            transition: "stroke-dasharray 0.75s cubic-bezier(0.4,0,0.2,1)",
          }}
        />
      </svg>
      <div style={{ position: "absolute", inset: 0, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: 1 }}>
        <span style={{ fontFamily: "Montserrat, sans-serif", fontWeight: 900, fontSize: 30, color: "var(--teal)", lineHeight: 1, textShadow: "0 0 20px rgba(20,184,166,0.55)" }}>{level}</span>
        <span style={{ fontFamily: "Roboto Mono, monospace", fontSize: 10, color: "rgba(255,255,255,0.4)", letterSpacing: "0.12em" }}>%</span>
      </div>
    </div>
  );
};

const SkillsSection = () => {
  const [active, setActive] = React.useState("workflow");
  const [isMobile, setIsMobile] = React.useState(() => window.innerWidth <= 768);
  const touchRef = React.useRef({ startX: null });
  const skill = SKILLS.find((s) => s.id === active);
  const activeIndex = SKILLS.findIndex((s) => s.id === active);

  const glassPanel = {
    background: "rgba(5,12,13,0.86)",
    border: "1px solid rgba(20,184,166,0.16)",
    boxShadow: "inset 0 1px 0 rgba(255,255,255,0.03), 0 10px 28px rgba(0,0,0,0.2)",
  };

  const mobileControlButton = {
    border: "1px solid rgba(20,184,166,0.16)",
    background: "rgba(5,12,13,0.86)",
    color: "rgba(255,255,255,0.86)",
    borderRadius: 999,
    padding: "10px 14px",
    fontFamily: "Montserrat, sans-serif",
    fontSize: 12,
    fontWeight: 700,
    cursor: "pointer",
    boxShadow: "inset 0 1px 0 rgba(255,255,255,0.03), 0 10px 28px rgba(0,0,0,0.2)",
  };

  React.useEffect(() => {
    const mediaQuery = window.matchMedia("(max-width: 768px)");
    const syncMobile = () => setIsMobile(mediaQuery.matches);
    syncMobile();
    mediaQuery.addEventListener("change", syncMobile);
    return () => mediaQuery.removeEventListener("change", syncMobile);
  }, []);

  const setActiveIndex = (nextIndex) => {
    const total = SKILLS.length;
    const normalized = (nextIndex + total) % total;
    setActive(SKILLS[normalized].id);
  };

  const handleTouchStart = (e) => {
    touchRef.current.startX = e.touches[0].clientX;
  };

  const handleTouchEnd = (e) => {
    if (touchRef.current.startX === null) return;
    const delta = touchRef.current.startX - e.changedTouches[0].clientX;
    touchRef.current.startX = null;
    if (Math.abs(delta) < 45) return;
    setActiveIndex(activeIndex + (delta > 0 ? 1 : -1));
  };

  return (
    <section
      data-screen-label="04 Skills"
      style={{
        minHeight: "100vh",
        padding: "100px 60px 80px",
        background: "var(--bg)",
        borderTop: "1px solid var(--border)",
        position: "relative",
        overflow: "hidden",
      }}
    >
      <video
        autoPlay
        muted
        loop
        playsInline
        src="uploads/background_teal_moving.mp4"
        onCanPlay={(e) => { e.target.playbackRate = 0.4; }}
        style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover", zIndex: 0 }}
      />
      <div style={{ position: "absolute", inset: 0, background: "rgba(0,0,0,0.60)", zIndex: 1 }} />

      <div style={{ maxWidth: 1100, margin: "0 auto", position: "relative", zIndex: 2 }}>
        <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", marginBottom: 48, flexWrap: "wrap", gap: 16 }}>
          <div>
            <p style={{ fontFamily: "Roboto Mono, monospace", fontSize: 11, fontWeight: 500, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--teal)", marginBottom: 14 }}>Expertise</p>
            <h2 style={{ fontFamily: "Montserrat, sans-serif", fontWeight: 900, fontSize: "clamp(2rem,4.5vw,3.2rem)", color: "var(--fg)", letterSpacing: "-0.025em", lineHeight: 1.05 }}>
              <span style={{ color: "var(--teal)", textShadow: "0 0 14px oklch(0.65 0.16 185 / 0.9), 0 0 32px oklch(0.65 0.16 185 / 0.5)", animation: "tealGlow 2.5s ease-in-out infinite" }}>Technical</span> Skills.
            </h2>
          </div>
          <p style={{ fontFamily: "Montserrat, sans-serif", fontSize: 15, color: "var(--muted)", maxWidth: 380, lineHeight: 1.7 }}>
            Full-stack automation across AI, CRM, APIs, and no-code platforms - delivering end-to-end solutions.
          </p>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "220px 1fr 280px", gap: 20, alignItems: "start" }}>
          {!isMobile && (
            <div style={{ ...glassPanel, borderRadius: 16, padding: 8 }}>
              <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
                {SKILLS.map((s, i) => (
                  <button
                    key={s.id}
                    onClick={() => setActive(s.id)}
                    style={{
                      display: "flex",
                      alignItems: "center",
                      gap: 12,
                      padding: "13px 16px",
                      borderRadius: 10,
                      border: "none",
                      cursor: "pointer",
                      background: active === s.id ? "rgba(20,184,166,0.1)" : "transparent",
                      borderLeft: active === s.id ? "2px solid var(--teal)" : "2px solid transparent",
                      textAlign: "left",
                      transition: "all 0.15s",
                      boxShadow: active === s.id ? "inset 0 1px 0 rgba(255,255,255,0.12)" : "none",
                    }}
                  >
                    <span
                      style={{
                        fontFamily: "Roboto Mono, monospace",
                        fontSize: 10,
                        fontWeight: 500,
                        color: active === s.id ? "var(--teal)" : "rgba(255,255,255,0.2)",
                        letterSpacing: "0.05em",
                        flexShrink: 0,
                        minWidth: 18,
                        transition: "color 0.15s",
                      }}
                    >
                      {String(i + 1).padStart(2, "0")}
                    </span>
                    <p
                      style={{
                        fontFamily: "Montserrat, sans-serif",
                        fontSize: 12,
                        fontWeight: active === s.id ? 700 : 500,
                        color: active === s.id ? "var(--teal)" : "rgba(255,255,255,0.45)",
                        lineHeight: 1.3,
                        margin: 0,
                        transition: "color 0.15s",
                      }}
                    >
                      {s.label}
                    </p>
                  </button>
                ))}
              </div>
            </div>
          )}

          <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
            {isMobile && (
              <div style={{ ...glassPanel, borderRadius: 16, padding: "14px 16px", display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, flexWrap: "wrap" }}>
                <div>
                  <p style={{ fontFamily: "Roboto Mono, monospace", fontSize: 10, color: "var(--teal)", letterSpacing: "0.18em", textTransform: "uppercase", marginBottom: 6 }}>Expertise</p>
                  <p style={{ fontFamily: "Montserrat, sans-serif", fontSize: 16, fontWeight: 800, color: "var(--fg)", margin: 0 }}>{skill.label}</p>
                </div>
                <div style={{ display: "flex", alignItems: "center", gap: 8, marginLeft: "auto" }}>
                  <button type="button" onClick={() => setActiveIndex(activeIndex - 1)} style={mobileControlButton}>Prev</button>
                  <p style={{ fontFamily: "Montserrat, sans-serif", fontSize: 13, fontWeight: 700, color: "rgba(126,230,219,0.88)", margin: 0, minWidth: 52, textAlign: "center" }}>
                    {String(activeIndex + 1).padStart(2, "0")} / {String(SKILLS.length).padStart(2, "0")}
                  </p>
                  <button type="button" onClick={() => setActiveIndex(activeIndex + 1)} style={mobileControlButton}>Next</button>
                </div>
              </div>
            )}

            <div
              key={active}
              style={{
                ...glassPanel,
                borderRadius: 16,
                overflow: "hidden",
                animation: "fadeIn 0.25s ease",
                touchAction: isMobile ? "pan-y" : "auto",
              }}
              onTouchStart={isMobile ? handleTouchStart : undefined}
              onTouchEnd={isMobile ? handleTouchEnd : undefined}
            >
              <div
                style={{
                  padding: isMobile ? "22px 18px" : "28px 32px",
                  borderBottom: "1px solid rgba(255,255,255,0.07)",
                  background: "rgba(20,184,166,0.04)",
                  display: "flex",
                  alignItems: isMobile ? "flex-start" : "center",
                  gap: isMobile ? 18 : 28,
                  flexDirection: isMobile ? "column" : "row",
                }}
              >
                <ArcGauge level={skill.level} size={isMobile ? 124 : 138} />
                <div>
                  <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 12 }}>
                    <div style={{ width: 32, height: 2, borderRadius: 2, background: "var(--teal)", boxShadow: "0 0 8px rgba(20,184,166,0.6)", flexShrink: 0 }} />
                    <span style={{ fontFamily: "Roboto Mono, monospace", fontSize: 10, color: "var(--teal)", letterSpacing: "0.22em", textTransform: "uppercase", opacity: 0.85 }}>Expertise</span>
                  </div>
                  <h3 style={{ fontFamily: "Montserrat, sans-serif", fontWeight: 900, fontSize: "clamp(16px,2vw,22px)", color: "var(--fg)", letterSpacing: "-0.02em", lineHeight: 1.2, marginBottom: 8 }}>{skill.label}</h3>
                  <p style={{ fontFamily: "Roboto Mono, monospace", fontSize: 10, color: "rgba(255,255,255,0.35)", letterSpacing: "0.1em", textTransform: "uppercase" }}>Proficiency Level</p>
                </div>
              </div>

              <div style={{ padding: isMobile ? "18px 16px 20px" : "24px 28px" }}>
                <p style={{ fontFamily: "Roboto Mono, monospace", fontSize: 10, color: "rgba(255,255,255,0.3)", letterSpacing: "0.2em", textTransform: "uppercase", marginBottom: 16 }}>Tools & Technologies</p>
                <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "1fr 1fr", gap: 10 }}>
                  {skill.items.map((item, i) => (
                    <div
                      key={item}
                      style={{
                        display: "flex",
                        alignItems: "center",
                        gap: 10,
                        padding: isMobile ? "12px 14px" : "12px 16px",
                        background: "rgba(255,255,255,0.03)",
                        border: "1px solid rgba(255,255,255,0.07)",
                        borderRadius: 10,
                        transition: "all 0.15s",
                        cursor: "default",
                        boxShadow: "inset 0 1px 0 rgba(255,255,255,0.06)",
                        animation: `fadeIn 0.3s ease ${i * 0.04}s both`,
                      }}
                      onMouseEnter={(e) => {
                        e.currentTarget.style.borderColor = "rgba(20,184,166,0.35)";
                        e.currentTarget.style.background = "rgba(20,184,166,0.07)";
                        e.currentTarget.style.boxShadow = "inset 0 1px 0 rgba(255,255,255,0.1), 0 0 12px rgba(20,184,166,0.1)";
                      }}
                      onMouseLeave={(e) => {
                        e.currentTarget.style.borderColor = "rgba(255,255,255,0.07)";
                        e.currentTarget.style.background = "rgba(255,255,255,0.03)";
                        e.currentTarget.style.boxShadow = "inset 0 1px 0 rgba(255,255,255,0.06)";
                      }}
                    >
                      <div style={{ width: 6, height: 6, borderRadius: "50%", background: "var(--teal)", flexShrink: 0, boxShadow: "0 0 6px rgba(20,184,166,0.7)" }} />
                      <span style={{ fontFamily: "Montserrat, sans-serif", fontSize: isMobile ? 14 : 13, fontWeight: 600, color: "var(--fg)" }}>{item}</span>
                    </div>
                  ))}
                </div>
              </div>

              {isMobile && (
                <div style={{ padding: "0 20px 18px", display: "flex", justifyContent: "center", gap: 8 }}>
                  {SKILLS.map((entry, index) => (
                    <button
                      key={entry.id}
                      onClick={() => setActive(entry.id)}
                      aria-label={entry.label}
                      style={{
                        width: index === activeIndex ? 22 : 7,
                        height: 7,
                        borderRadius: 999,
                        border: "none",
                        padding: 0,
                        cursor: "pointer",
                        background: index === activeIndex ? "var(--teal)" : "rgba(255,255,255,0.18)",
                        boxShadow: index === activeIndex ? "0 0 10px rgba(20,184,166,0.35)" : "none",
                        transition: "all 0.2s ease",
                      }}
                    />
                  ))}
                </div>
              )}
            </div>
          </div>

          {!isMobile && (
            <div style={{ ...glassPanel, borderRadius: 14, padding: "22px 22px" }}>
              <p style={{ fontFamily: "Roboto Mono, monospace", fontSize: 10, color: "var(--teal)", letterSpacing: "0.18em", textTransform: "uppercase", marginBottom: 16 }}>All Platforms</p>
              <div style={{ display: "flex", flexWrap: "wrap", gap: 7 }}>
                {PLATFORMS.map((p) => (
                  <span
                    key={p.name}
                    style={{
                      fontFamily: "Roboto Mono, monospace",
                      fontSize: 10,
                      color: "rgba(255,255,255,0.45)",
                      background: "rgba(255,255,255,0.025)",
                      border: "1px solid rgba(20,184,166,0.12)",
                      borderRadius: 6,
                      padding: "5px 11px",
                      letterSpacing: "0.04em",
                      cursor: "default",
                      transition: "all 0.2s",
                      boxShadow: "inset 0 1px 0 rgba(255,255,255,0.03)",
                      display: "inline-block",
                    }}
                    onMouseEnter={(e) => {
                      e.target.style.borderColor = "rgba(20,184,166,0.5)";
                      e.target.style.color = "var(--teal)";
                      e.target.style.background = "rgba(20,184,166,0.08)";
                      e.target.style.boxShadow = "inset 0 1px 0 rgba(255,255,255,0.1), 0 0 12px rgba(20,184,166,0.2)";
                    }}
                    onMouseLeave={(e) => {
                      e.target.style.borderColor = "rgba(20,184,166,0.12)";
                      e.target.style.color = "rgba(255,255,255,0.45)";
                      e.target.style.background = "rgba(255,255,255,0.025)";
                      e.target.style.boxShadow = "inset 0 1px 0 rgba(255,255,255,0.03)";
                    }}
                  >
                    {p.name}
                  </span>
                ))}
              </div>
            </div>
          )}
        </div>
      </div>
    </section>
  );
};

Object.assign(window, { SkillsSection });
