function AssessmentModalShell({ onClose, children }) {
  React.useEffect(() => {
    const onKey = (e) => {
      if (e.key === "Escape") onClose();
    };
    document.addEventListener("keydown", onKey);
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => {
      document.removeEventListener("keydown", onKey);
      document.body.style.overflow = prevOverflow;
    };
  }, [onClose]);

  return ReactDOM.createPortal(
    <div
      className="pu-modal-backdrop"
      onClick={(e) => {
        if (e.target === e.currentTarget) onClose();
      }}
      role="presentation"
    >
      <div className="pu-modal" role="dialog" aria-modal="true" aria-labelledby="assessment-title">
        <button type="button" className="pu-modal-close" onClick={onClose} aria-label="Close assessment">
          ×
        </button>
        {children}
      </div>
    </div>,
    document.body
  );
}

function ProducerAssessment({ onClose }) {
  const [currentSection, setCurrentSection] = React.useState(0);
  const [responses, setResponses] = React.useState({});
  const [showResult, setShowResult] = React.useState(false);

  const sections = [
    {
      title: "Your Music & Revenue",
      description: "Let's start with the tangible side of your production journey.",
      questions: [
        {
          id: "placements",
          type: "select",
          label: "How many placements have you secured?",
          options: [
            { value: "0", label: "Zero, never had a placement" },
            { value: "1-3", label: "1–3 placements (small projects, YouTube, etc.)" },
            { value: "4-10", label: "4–10 placements across various platforms" },
            { value: "11+", label: "11+ placements, some with meaningful reach" }
          ]
        },
        {
          id: "music_income",
          type: "select",
          label: "Have you made money directly from music (placements, licensing, streaming, beats, etc.)?",
          options: [
            { value: "never", label: "Never, zero income from music" },
            { value: "sporadic", label: "Sporadic income (under $500 total)" },
            { value: "some", label: "Some income ($500–$5k total)" },
            { value: "regular", label: "Regular monthly income from music" },
            { value: "substantial", label: "Substantial income (music is a primary revenue source)" }
          ]
        },
        {
          id: "streams",
          type: "select",
          label: "How many total streams do you have across all platforms (Spotify, Apple Music, YouTube, SoundCloud, etc.)?",
          options: [
            { value: "0-10k", label: "Zero or under 10,000 streams" },
            { value: "10k-1m", label: "10,000 to a million" },
            { value: "1m-10m", label: "1 million to 10 million" },
            { value: "10m-100m", label: "10 million to 100 million" },
            { value: "100m-1b", label: "100 million to a billion" }
          ]
        },
        {
          id: "social_activity",
          type: "select",
          label: "Are you actively creating and sharing your music on social media, or mostly consuming?",
          options: [
            { value: "consuming", label: "Mostly consuming, not really putting work out there yet" },
            { value: "creating_not_sharing", label: "Creating but rarely sharing" },
            { value: "sometimes", label: "Creating and sharing sometimes (inconsistent)" },
            { value: "regular", label: "Creating and sharing regularly (active presence)" },
            { value: "very_active", label: "Very active, constantly creating and engaging with audience" }
          ]
        }
      ]
    },
    {
      title: "Your Niche & Position",
      description: "Where do you sit in the music industry landscape?",
      questions: [
        {
          id: "niche_clarity",
          type: "select",
          label: "How clear are you on your niche or lane?",
          options: [
            { value: "unclear", label: "Totally unclear, I make different stuff, not sure where I fit" },
            { value: "emerging", label: "Emerging sense, I'm experimenting but starting to see a pattern" },
            { value: "defined", label: "Pretty defined, I know my sound and who I'm making for" },
            { value: "owned", label: "Very owned, I'm known for a specific sound/style in my circles" }
          ]
        },
        {
          id: "target_listener",
          type: "select",
          label: "When you make music, who do you imagine listening to it?",
          options: [
            { value: "no_one", label: "No one specific, I just make what feels right" },
            { value: "vague", label: "Vague sense, people like me, but I'm not super clear" },
            { value: "specific", label: "Specific type of person or artist, I know who'd vibe with it" },
            { value: "very_clear", label: "Very clear, I have a specific listener or collaborator in mind every time" }
          ]
        },
        {
          id: "primary_goal",
          type: "select",
          label: "What's your primary goal in music right now?",
          options: [
            { value: "unsure", label: "Not sure yet, still exploring" },
            { value: "better_skills", label: "Get better at producing and have a solid catalog" },
            { value: "placements", label: "Get placements and make money from my music" },
            { value: "brand", label: "Build a recognizable brand or reputation" },
            { value: "collab", label: "Collaborate with other artists or get signed" }
          ]
        }
      ]
    },
    {
      title: "Your Network & Opportunities",
      description: "How connected are you in the industry?",
      questions: [
        {
          id: "industry_relationships",
          type: "select",
          label: "How many meaningful professional relationships do you have in music?",
          options: [
            { value: "isolated", label: "Very few or none, mostly working solo" },
            { value: "emerging", label: "A handful (3–5 people I can reach out to)" },
            { value: "solid", label: "Solid network (10–20 people; regular collaborations)" },
            { value: "strong", label: "Strong network (20+ people; regular opportunities from connections)" }
          ]
        },
        {
          id: "collab_frequency",
          type: "select",
          label: "How often do you collaborate or get work from industry connections?",
          options: [
            { value: "never", label: "Never, I don't get opportunities this way" },
            { value: "rare", label: "Rarely (once a year or less)" },
            { value: "sometimes", label: "Sometimes (a few times per year)" },
            { value: "regular", label: "Regular (monthly or more)" }
          ]
        },
        {
          id: "opportunity_source",
          type: "select",
          label: "Where do most of your opportunities come from?",
          options: [
            { value: "none", label: "I don't have consistent opportunities yet" },
            { value: "cold", label: "Cold outreach or luck (finding my own)" },
            { value: "referral", label: "Referrals from people I know" },
            { value: "reputation", label: "People seeking me out because of my reputation" },
            { value: "mixed", label: "Mix of all of the above" }
          ]
        }
      ]
    },
    {
      title: "Your Knowledge & Confidence",
      description: "How strategically clear are you about your path?",
      questions: [
        {
          id: "strategy_clarity",
          type: "select",
          label: "How clear is your strategy for growing as a producer/artist?",
          options: [
            { value: "no_strategy", label: "No strategy, I'm just making and hoping" },
            { value: "emerging", label: "Emerging strategy, I have some ideas but not fully formed" },
            { value: "clear", label: "Clear strategy, I know the steps to take" },
            { value: "executing", label: "Executing, I'm actively following a strategic plan" }
          ]
        },
        {
          id: "knowledge_gaps",
          type: "select",
          label: "What are your biggest knowledge gaps right now?",
          options: [
            { value: "production", label: "Production skills (music theory, arrangement, mixing)" },
            { value: "business", label: "Business/industry knowledge (licensing, contracts, positioning)" },
            { value: "both", label: "Both equally" },
            { value: "neither", label: "I feel pretty competent, more execution issues" }
          ]
        },
        {
          id: "biggest_challenge",
          type: "select",
          label: "What's your biggest current challenge?",
          options: [
            { value: "making", label: "Making music I'm proud of / improving production skills" },
            { value: "positioning", label: "Positioning myself / finding my niche" },
            { value: "opportunities", label: "Getting consistent opportunities / placements" },
            { value: "execution", label: "Executing my plan / staying consistent" },
            { value: "scaling", label: "Scaling or monetizing what I already have" }
          ]
        }
      ]
    },
    {
      title: "Your Mindset & Commitment",
      description: "How serious are you about this?",
      questions: [
        {
          id: "commitment_level",
          type: "select",
          label: "How committed are you to music right now?",
          options: [
            { value: "hobby", label: "Hobby/fun, not trying to make a career" },
            { value: "serious_hobby", label: "Serious hobby, I invest time but not sure about career" },
            { value: "pursuing", label: "Actively pursuing, I want this to be my career" },
            { value: "all_in", label: "All in, building this as my primary income" }
          ]
        },
        {
          id: "time_investment",
          type: "select",
          label: "How much time per week do you invest in music (learning, making, marketing)?",
          options: [
            { value: "less_5", label: "Less than 5 hours/week" },
            { value: "5-15", label: "5–15 hours/week" },
            { value: "15-30", label: "15–30 hours/week" },
            { value: "30+", label: "30+ hours/week (substantial commitment)" }
          ]
        },
        {
          id: "mentorship_openness",
          type: "select",
          label: "How open are you to feedback and mentorship?",
          options: [
            { value: "closed", label: "Prefer to figure it out myself" },
            { value: "somewhat", label: "Open to feedback but like doing my own thing" },
            { value: "very", label: "Very open, I actively seek guidance" },
            { value: "eager", label: "Eager, I actively want structured feedback" }
          ]
        }
      ]
    },
    {
      title: "Your Vision",
      description: "Where do you want to go?",
      questions: [
        {
          id: "one_year_vision",
          type: "select",
          label: "Where do you want to be in one year?",
          options: [
            { value: "unclear", label: "Unclear, still figuring out what I want" },
            { value: "better_skills", label: "Better production skills / stronger catalog" },
            { value: "some_revenue", label: "Some consistent revenue from music ($200-$1k/month)" },
            { value: "solid_revenue", label: "Solid revenue ($1k-$5k/month) with clear positioning" },
            { value: "significant", label: "Significant income ($5k+/month) or industry recognition" }
          ]
        },
        {
          id: "success_definition",
          type: "select",
          label: "How do you define success in music?",
          options: [
            { value: "creative", label: "Making music I'm proud of" },
            { value: "impact", label: "Making an impact (listeners, followers, recognition)" },
            { value: "revenue", label: "Making money from music" },
            { value: "career", label: "Building a sustainable music career" },
            { value: "hybrid", label: "Mix of creative satisfaction + real income" }
          ]
        }
      ]
    }
  ];

  const scoringLogic = (responses) => {
    let score = 0;
    let flags = [];

    if (responses.placements === "0") flags.push("zero_placements");
    if (responses.music_income === "never") flags.push("zero_income");

    if (flags.includes("zero_placements") && flags.includes("zero_income")) {
      return {
        tier: "Beginner",
        confidence: "high",
        reasoning: "No placements and no music income are clear indicators you're at the beginning of your journey."
      };
    }

    const placementScore = { "0": 0, "1-3": 2, "4-10": 4, "11+": 6 }[responses.placements] || 0;
    const incomeScore = { "never": 0, "sporadic": 2, "some": 4, "regular": 6, "substantial": 8 }[responses.music_income] || 0;
    const streamsScore = { "0-10k": 0, "10k-1m": 2, "1m-10m": 4, "10m-100m": 6, "100m-1b": 8 }[responses.streams] || 0;
    const socialScore = { "consuming": 0, "creating_not_sharing": 1, "sometimes": 2, "regular": 3, "very_active": 4 }[responses.social_activity] || 0;
    const nicheScore = { "unclear": 0, "emerging": 2, "defined": 4, "owned": 6 }[responses.niche_clarity] || 0;
    const targetScore = { "no_one": 0, "vague": 1, "specific": 3, "very_clear": 4 }[responses.target_listener] || 0;
    const goalScore = { "unsure": 0, "better_skills": 2, "placements": 4, "brand": 4, "collab": 4 }[responses.primary_goal] || 0;
    const networkScore = { "isolated": 0, "emerging": 2, "solid": 4, "strong": 6 }[responses.industry_relationships] || 0;
    const strategyScore = { "no_strategy": 0, "emerging": 2, "clear": 4, "executing": 6 }[responses.strategy_clarity] || 0;
    const commitmentScore = { "hobby": 0, "serious_hobby": 1, "pursuing": 3, "all_in": 4 }[responses.commitment_level] || 0;

    score = placementScore + incomeScore + streamsScore + socialScore + nicheScore + targetScore + goalScore + networkScore + strategyScore + commitmentScore;

    if (score <= 15) {
      return {
        tier: "Beginner",
        confidence: "medium",
        reasoning: "You're at the foundation stage. Focus on creating consistently and exploring your niche."
      };
    } else if (score <= 30) {
      return {
        tier: "Intermediate",
        confidence: "medium",
        reasoning: "You have momentum and some proof points. Time to strategize and scale intentionally."
      };
    } else {
      return {
        tier: "Advanced",
        confidence: "high",
        reasoning: "You've proven success and have clarity. Ready to deepen expertise and scale."
      };
    }
  };

  const handleResponse = (questionId, value) => {
    setResponses({ ...responses, [questionId]: value });
  };

  const handleNext = () => {
    if (currentSection < sections.length - 1) {
      setCurrentSection(currentSection + 1);
    } else {
      setShowResult(true);
    }
  };

  const handlePrev = () => {
    if (currentSection > 0) {
      setCurrentSection(currentSection - 1);
    }
  };

  const result = scoringLogic(responses);

  const tierDescriptions = {
    Beginner: {
      description: "You're building your foundation. Focus on creating consistently, developing your unique sound, and understanding how the music industry works. Your community teaches strategy, positioning, and industry knowledge, for production skills, check out YouTube tutorials.",
      next_step: "Join the Free Community to learn the fundamentals of industry positioning, niche clarity, and how to think strategically about your music career. You'll get clarity on your direction and start building momentum.",
      icon: "🌱"
    },
    Intermediate: {
      description: "You have momentum and proof points. You understand your niche and have some revenue or opportunities. Now it's time to strategize, scale systematically, and position yourself for bigger opportunities.",
      next_step: "Join the Paid Community to deepen your strategic thinking, learn how to attract better opportunities, and build a sustainable path forward.",
      icon: "🚀"
    },
    Advanced: {
      description: "You've proven success and have strategic clarity. You're executing well, but you're ready to go deeper — whether that's mastering a specific skill, breaking into a new market, or scaling to the next level.",
      next_step: "Join Producer Union Plus — the Roadmap, worksheets, and weekly live calls are built for where you are. Once you're in, message us on Skool and let us know the assessment ranked you Advanced.",
      icon: "🎯"
    }
  };

  if (showResult) {
    const tierInfo = tierDescriptions[result.tier];
    return (
      <AssessmentModalShell onClose={onClose}>
          <div style={{ textAlign: "center", marginBottom: 32 }}>
            <div style={{ fontSize: 48, marginBottom: 16 }}>{tierInfo.icon}</div>
            <h1 id="assessment-title" style={{ fontFamily: "var(--sans)", fontSize: "clamp(26px, 4vw, 32px)", fontWeight: 800, color: "var(--ink)", marginBottom: 8, letterSpacing: "-0.025em" }}>
              You're a <span style={{ color: "var(--gold)" }}>{result.tier}</span> Producer
            </h1>
            <p style={{ color: "var(--ink-2)", fontSize: 16, lineHeight: 1.5 }}>{result.reasoning}</p>
          </div>

          <div style={{ background: "rgba(212,166,74,0.08)", padding: 24, marginBottom: 24, border: "1px solid var(--rule-gold)" }}>
            <h2 style={{ fontFamily: "var(--sans)", fontSize: 16, fontWeight: 700, color: "var(--ink)", marginBottom: 12 }}>What This Means</h2>
            <p style={{ color: "var(--ink-2)", lineHeight: 1.6, fontSize: 15 }}>{tierInfo.description}</p>
          </div>

          <div style={{ background: "rgba(255,255,255,0.03)", padding: 24, marginBottom: 32, border: "1px solid var(--rule-strong)" }}>
            <h2 style={{ fontFamily: "var(--sans)", fontSize: 16, fontWeight: 700, color: "var(--ink)", marginBottom: 12 }}>Next Step</h2>
            <p style={{ color: "var(--ink-2)", lineHeight: 1.6, fontSize: 15 }}>{tierInfo.next_step}</p>
          </div>

          <div style={{ display: "flex", gap: 12, flexWrap: "wrap" }}>
            {result.tier === "Advanced" ? (
              <a href={PU_LINKS.plus} className="btn btn-primary" style={{ flex: 1, minWidth: 140, justifyContent: "center" }}>
                Join Plus
              </a>
            ) : (
              <button
                type="button"
                onClick={() => {
                  setShowResult(false);
                  setCurrentSection(0);
                  setResponses({});
                }}
                className="btn btn-primary"
                style={{ flex: 1, minWidth: 140, justifyContent: "center" }}
              >
                Retake Assessment
              </button>
            )}
            <button type="button" onClick={onClose} className="btn btn-ghost" style={{ flex: 1, minWidth: 140, justifyContent: "center" }}>
              Close
            </button>
          </div>
      </AssessmentModalShell>
    );
  }

  const section = sections[currentSection];
  const allQuestionsAnswered = section.questions.every(q => responses[q.id] !== undefined);

  return (
    <AssessmentModalShell onClose={onClose}>
        <div style={{ marginBottom: 28, paddingRight: 36 }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 16, gap: 12 }}>
            <h1 id="assessment-title" style={{ fontFamily: "var(--sans)", fontSize: "clamp(22px, 3vw, 28px)", fontWeight: 800, color: "var(--ink)", letterSpacing: "-0.02em", margin: 0 }}>
              Producer Assessment
            </h1>
            <span className="caption">{currentSection + 1} of {sections.length}</span>
          </div>
          <div style={{ width: "100%", background: "rgba(255,255,255,0.08)", height: 6 }}>
            <div
              style={{
                background: "var(--gold)",
                height: 6,
                transition: "width 0.3s ease",
                width: `${((currentSection + 1) / sections.length) * 100}%`,
              }}
            />
          </div>
        </div>

        <div style={{ marginBottom: 28 }}>
          <h2 style={{ fontFamily: "var(--sans)", fontSize: 20, fontWeight: 700, color: "var(--ink)", marginBottom: 8, letterSpacing: "-0.015em" }}>{section.title}</h2>
          <p style={{ color: "var(--ink-2)", fontSize: 15, lineHeight: 1.5 }}>{section.description}</p>
        </div>

        <div style={{ marginBottom: 28, display: "flex", flexDirection: "column", gap: 24 }}>
          {section.questions.map((question) => (
            <div key={question.id}>
              <label style={{ display: "block", fontFamily: "var(--sans)", fontSize: 14, fontWeight: 600, color: "var(--ink)", marginBottom: 12 }}>
                {question.label}
              </label>
              <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                {question.options.map((option) => {
                  const selected = responses[question.id] === option.value;
                  return (
                    <button
                      key={option.value}
                      type="button"
                      onClick={() => handleResponse(question.id, option.value)}
                      style={{
                        textAlign: "left",
                        padding: "14px 16px",
                        border: `1px solid ${selected ? "var(--rule-gold)" : "var(--rule-strong)"}`,
                        background: selected ? "rgba(212,166,74,0.10)" : "rgba(255,255,255,0.02)",
                        cursor: "pointer",
                        transition: "all 0.18s ease",
                        color: "var(--ink-2)",
                        fontFamily: "var(--sans)",
                        fontSize: 14,
                        lineHeight: 1.45,
                      }}
                    >
                      <div style={{ display: "flex", alignItems: "flex-start", gap: 12 }}>
                        <span style={{
                          width: 18, height: 18, flexShrink: 0, marginTop: 2,
                          border: `2px solid ${selected ? "var(--gold)" : "var(--ink-4)"}`,
                          background: selected ? "var(--gold)" : "transparent",
                          display: "inline-block",
                        }} />
                        <span>{option.label}</span>
                      </div>
                    </button>
                  );
                })}
              </div>
            </div>
          ))}
        </div>

        <div style={{ display: "flex", gap: 12, flexWrap: "wrap" }}>
          <button
            type="button"
            onClick={handlePrev}
            disabled={currentSection === 0}
            className="btn btn-ghost"
            style={{ opacity: currentSection === 0 ? 0.4 : 1, cursor: currentSection === 0 ? "not-allowed" : "pointer" }}
          >
            ← Previous
          </button>
          <button
            type="button"
            onClick={handleNext}
            disabled={!allQuestionsAnswered}
            className="btn btn-primary"
            style={{ flex: 1, minWidth: 160, justifyContent: "center", opacity: !allQuestionsAnswered ? 0.5 : 1, cursor: !allQuestionsAnswered ? "not-allowed" : "pointer" }}
          >
            {currentSection === sections.length - 1 ? "See Results" : "Next"} →
          </button>
        </div>
    </AssessmentModalShell>
  );
}

window.ProducerAssessment = ProducerAssessment;
