/* global React, TextReveal, SectionHead, Img */

const { useState: useStateOp, useEffect: useEffectOp } = React;

/* ============================================================
   OPPORTUNITY — Software Developer Internship (Live Project)
   Not linked in navbar. Reachable via #opportunity hash.
============================================================ */
function Opportunity({ setRoute }) {
  const [data, setData] = useStateOp({
    firstName: "",
    lastName: "",
    email: "",
    mobile: "",
    address: "",
  });
  const [touched, setTouched] = useStateOp(false);
  const [sent, setSent] = useStateOp(false);
  const [sending, setSending] = useStateOp(false);
  const [error, setError] = useStateOp("");

  const update = (k, v) => setData((d) => ({ ...d, [k]: v }));

  const isFilled =
    data.firstName.trim() &&
    data.lastName.trim() &&
    data.email.trim() &&
    /^\S+@\S+\.\S+$/.test(data.email) &&
    data.mobile.trim().length >= 7 &&
    data.address.trim();

  const onSubmit = async (e) => {
    e.preventDefault();
    setTouched(true);
    setError("");
    if (!isFilled || sending) return;

    setSending(true);

    // ----------------------------------------------------------
    // POST to PrintBala internship API
    // ----------------------------------------------------------
    const endpoint = "https://api2.printbala.in:2026/api/OpenForms/ApplyInternsip";

    const payload = {
      FirstName: data.firstName.trim(),
      LastName: data.lastName.trim(),
      Email: data.email.trim(),
      Mobile: data.mobile.trim(),
      Address: data.address.trim(),
    };

    try {
      const res = await fetch(endpoint, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Accept: "application/json",
        },
        body: JSON.stringify(payload),
      });

      const text = await res.text();
      let json = {};
      try { json = text ? JSON.parse(text) : {}; } catch (_) { /* non-JSON body is fine */ }

      // API returns { StatusCode: 1, Message: "...", Data: {...} } on success
      const apiOk =
        json.StatusCode === 1 ||
        json.statusCode === 1 ||
        json.success === true ||
        json.Success === true;

      if (res.ok && (apiOk || json.StatusCode === undefined)) {
        setSent(true);
      } else {
        throw new Error(
          json.Message || json.message || `Server responded with ${res.status}`
        );
      }
    } catch (err) {
      setError(
        "We couldn't submit your application right now. Please try again in a minute, or email your details to hr@printbala.com directly."
      );
      console.error("[Opportunity] application submit failed:", err);
    } finally {
      setSending(false);
    }
  };

  const scrollToApply = () => {
    const el = document.getElementById("apply");
    if (el) el.scrollIntoView({ behavior: "smooth", block: "start" });
  };

  return (
    <main>
      {/* HERO */}
      <header className="page-header" style={{ position: "relative", overflow: "hidden" }}>
        <div
          aria-hidden
          style={{
            position: "absolute",
            inset: 0,
            background:
              "radial-gradient(60% 80% at 20% 0%, var(--accent-soft) 0%, transparent 60%), radial-gradient(50% 70% at 100% 20%, var(--accent-soft) 0%, transparent 55%)",
            opacity: 0.6,
            pointerEvents: "none",
          }}
        />
        <div className="container" style={{ position: "relative" }}>
          <div className="crumbs reveal">Home / Opportunity</div>

          <div
            className="reveal"
            data-delay="2"
            style={{
              display: "inline-flex",
              alignItems: "center",
              gap: 10,
              padding: "8px 14px",
              border: "1px solid var(--line-strong)",
              borderRadius: "var(--radius-pill)",
              background: "var(--bg-elev)",
              fontSize: 12,
              fontFamily: "var(--font-mono)",
              letterSpacing: "0.16em",
              textTransform: "uppercase",
              color: "var(--accent)",
              marginBottom: 20,
            }}
          >
            <span
              style={{
                width: 8,
                height: 8,
                borderRadius: "50%",
                background: "var(--accent)",
                boxShadow: "0 0 0 4px color-mix(in oklch, var(--accent) 25%, transparent)",
              }}
            />
            Now hiring · Internship
          </div>

          <div
            className="reveal"
            data-delay="2"
            style={{
              display: "flex",
              alignItems: "center",
              gap: 10,
              fontSize: 13,
              fontFamily: "var(--font-mono)",
              color: "var(--ink-3)",
              marginBottom: 14,
              letterSpacing: "0.04em",
            }}
          >
            <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.8">
              <rect x="3" y="5" width="18" height="16" rx="2" />
              <path d="M3 9h18M8 3v4M16 3v4" />
            </svg>
            <span>Posted</span>
            <span style={{ color: "var(--ink-2)", fontWeight: 500 }}>22 May 2026</span>
          </div>

          <TextReveal as="h1">
            Software Developer Intern — work on a live PrintBala project.
          </TextReveal>
          <p className="lede reveal" data-delay="3">
            Hands-on internship building real features that ship to thousands of businesses.
            Remote-friendly, 4–5 hours a day, daily standup with the engineering team.
          </p>

          <div
            className="reveal"
            data-delay="4"
            style={{ marginTop: 32, display: "flex", gap: 12, flexWrap: "wrap" }}
          >
            <button className="btn btn-primary" onClick={scrollToApply}>
              Apply now
              <svg className="arrow" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <path d="M5 12h14M13 5l7 7-7 7" />
              </svg>
            </button>
            <a href="#details" className="btn btn-ghost">View role details</a>
          </div>

          {/* Quick facts */}
          <div
            className="reveal"
            data-delay="5"
            style={{
              marginTop: 48,
              display: "grid",
              gridTemplateColumns: "repeat(4, 1fr)",
              gap: 16,
            }}
          >
            {[
              { k: "Role", v: "Software Developer Intern" },
              { k: "Type", v: "Internship · Unpaid" },
              { k: "Location", v: "Remote" },
              { k: "Commitment", v: "4–5 hours / day" },
            ].map((f) => (
              <div
                key={f.k}
                style={{
                  background: "var(--bg-elev)",
                  border: "1px solid var(--line)",
                  borderRadius: "var(--radius-md)",
                  padding: "18px 20px",
                }}
              >
                <div
                  className="mono"
                  style={{
                    fontSize: 11,
                    letterSpacing: "0.18em",
                    color: "var(--ink-3)",
                    textTransform: "uppercase",
                    marginBottom: 6,
                  }}
                >
                  {f.k}
                </div>
                <div
                  style={{
                    color: "var(--ink)",
                    fontFamily: "var(--font-display)",
                    fontWeight: 600,
                    fontSize: 17,
                    letterSpacing: "-0.01em",
                  }}
                >
                  {f.v}
                </div>
              </div>
            ))}
          </div>

          <style>{`
            @media (max-width: 900px) {
              .page-header [style*="grid-template-columns: repeat(4"] { grid-template-columns: repeat(2, 1fr) !important; }
            }
          `}</style>
        </div>
      </header>

      {/* HIGHLIGHTS */}
      <section className="section" id="details">
        <div className="container">
          <SectionHead
            eyebrow="What you get"
            title="A real role, not a coffee run."
            sub="You will write code that goes to production. You will sit in the same standup as our senior engineers."
          />

          <div
            style={{
              display: "grid",
              gridTemplateColumns: "repeat(3, 1fr)",
              gap: 16,
            }}
            className="opp-highlights"
          >
            {[
              {
                ic: (
                  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6">
                    <path d="M3 7h18M3 12h18M3 17h12" />
                    <circle cx="19" cy="17" r="2" />
                  </svg>
                ),
                h: "Live project",
                b: "Ship real features to the PrintBala platform — order flows, partner portal, internal tooling. Your commits go to production.",
              },
              {
                ic: (
                  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6">
                    <rect x="3" y="4" width="18" height="13" rx="2" />
                    <path d="M8 21h8M12 17v4" />
                  </svg>
                ),
                h: "Remote opportunity",
                b: "Work from anywhere in India. We give you the brief, the codebase, and the support — you bring the laptop and the focus.",
              },
              {
                ic: (
                  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6">
                    <circle cx="12" cy="12" r="9" />
                    <path d="M12 7v5l3 2" />
                  </svg>
                ),
                h: "Daily standup",
                b: "Join a 15-min standup every morning with the engineering team. Share what you shipped, what's next, where you're stuck.",
              },
            ].map((c) => (
              <div
                key={c.h}
                className="reveal"
                style={{
                  background: "var(--bg-elev)",
                  border: "1px solid var(--line)",
                  borderRadius: "var(--radius-lg)",
                  padding: "32px 28px",
                  display: "flex",
                  flexDirection: "column",
                  gap: 14,
                }}
              >
                <div
                  style={{
                    width: 44,
                    height: 44,
                    borderRadius: "var(--radius-md)",
                    background: "var(--accent-soft)",
                    color: "var(--accent-deep)",
                    display: "grid",
                    placeItems: "center",
                  }}
                >
                  <span style={{ display: "inline-block", width: 22, height: 22 }}>{c.ic}</span>
                </div>
                <h3 style={{ fontSize: 22, color: "var(--ink)", letterSpacing: "-0.02em", margin: 0 }}>{c.h}</h3>
                <p style={{ color: "var(--ink-3)", fontSize: 15, margin: 0 }}>{c.b}</p>
              </div>
            ))}
          </div>

          <style>{`
            @media (max-width: 900px) {
              .opp-highlights { grid-template-columns: 1fr !important; }
            }
          `}</style>
        </div>
      </section>

      {/* HONEST EXPECTATIONS */}
      <section className="section" style={{ background: "var(--bg-soft)", paddingTop: 64, paddingBottom: 64 }}>
        <div className="container">
          <div
            className="reveal"
            style={{
              display: "grid",
              gridTemplateColumns: "1.1fr 1fr",
              gap: 32,
              alignItems: "start",
            }}
          >
            <div>
              <div className="eyebrow" style={{ marginBottom: 18 }}>Before you apply</div>
              <h2 style={{ fontSize: 38, color: "var(--ink)", letterSpacing: "-0.03em", marginBottom: 16 }}>
                Be honest about your fit.
              </h2>
              <p style={{ color: "var(--ink-2)", fontSize: 17 }}>
                We're upfront about the terms so we both save time. Apply only if every point below is a yes.
              </p>
            </div>

            <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 14 }}>
              {[
                "This is an unpaid internship. There is no stipend.",
                "Only serious candidates — we expect you to treat it like a real job.",
                "4–5 hours of focused work every day, on weekdays.",
                "You join the daily standup on time, with your update ready.",
                "You ship a daily task to your engineering lead.",
                "Strong performers are offered a paid full-time role at the end.",
              ].map((p) => (
                <li
                  key={p}
                  style={{
                    display: "flex",
                    gap: 14,
                    alignItems: "flex-start",
                    background: "var(--bg-elev)",
                    border: "1px solid var(--line)",
                    borderRadius: "var(--radius-md)",
                    padding: "14px 16px",
                  }}
                >
                  <span
                    style={{
                      flex: "0 0 22px",
                      width: 22,
                      height: 22,
                      borderRadius: "50%",
                      background: "var(--accent)",
                      color: "var(--accent-ink)",
                      display: "grid",
                      placeItems: "center",
                      marginTop: 2,
                    }}
                  >
                    <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="3">
                      <path d="M5 12l5 5L20 7" />
                    </svg>
                  </span>
                  <span style={{ color: "var(--ink-2)", fontSize: 16, lineHeight: 1.55 }}>{p}</span>
                </li>
              ))}
            </ul>
          </div>

          <style>{`
            @media (max-width: 900px) {
              section[style*="background: var(--bg-soft)"] .reveal[style*="grid-template-columns: 1.1fr 1fr"] {
                grid-template-columns: 1fr !important;
              }
            }
          `}</style>
        </div>
      </section>

      {/* DAILY RHYTHM */}
      <section className="section">
        <div className="container">
          <SectionHead
            eyebrow="A day in the role"
            title="Predictable rhythm. Real output."
            sub=""
          />

          <div
            className="reveal opp-day-grid"
            style={{
              display: "grid",
              gridTemplateColumns: "repeat(4, 1fr)",
              gap: 16,
            }}
          >
            {[
              {
                t: "10:00",
                h: "Daily standup",
                b: "15-min sync. Share yesterday's progress, today's plan, any blockers. Cameras on.",
              },
              {
                t: "10:15",
                h: "Focused build",
                b: "Pick up your assigned daily task — feature work, bug fix, or polish. Code, test, push a PR.",
              },
              {
                t: "01:00",
                h: "Review & pairing",
                b: "Get your PR reviewed by your lead. Quick pairing if you're stuck. Push fixes.",
              },
              {
                t: "02:30",
                h: "Wrap-up",
                b: "Ship a short end-of-day update in the team channel. Hand off, log learnings, sign off.",
              },
            ].map((s, i) => (
              <div
                key={s.h}
                style={{
                  background: "var(--bg-elev)",
                  border: "1px solid var(--line)",
                  borderRadius: "var(--radius-lg)",
                  padding: "24px 22px",
                  position: "relative",
                }}
              >
                <div
                  className="mono"
                  style={{
                    fontSize: 12,
                    color: "var(--accent)",
                    letterSpacing: "0.2em",
                    marginBottom: 10,
                  }}
                >
                  {String(i + 1).padStart(2, "0")} · {s.t}
                </div>
                <h4 style={{ fontSize: 18, color: "var(--ink)", margin: "0 0 8px", letterSpacing: "-0.01em" }}>{s.h}</h4>
                <p style={{ fontSize: 14, color: "var(--ink-3)", margin: 0 }}>{s.b}</p>
              </div>
            ))}
          </div>

          <style>{`
            @media (max-width: 900px) {
              .opp-day-grid { grid-template-columns: repeat(2, 1fr) !important; }
            }
            @media (max-width: 560px) {
              .opp-day-grid { grid-template-columns: 1fr !important; }
            }
          `}</style>
        </div>
      </section>

      {/* WHAT WE LOOK FOR */}
      <section className="section" style={{ background: "var(--bg-soft)" }}>
        <div className="container">
          <div
            style={{
              display: "grid",
              gridTemplateColumns: "1fr 1fr",
              gap: 32,
            }}
            className="opp-look-grid"
          >
            <div className="reveal">
              <div className="eyebrow" style={{ marginBottom: 18 }}>What we look for</div>
              <h3 style={{ fontSize: 28, color: "var(--ink)", letterSpacing: "-0.02em", marginBottom: 16 }}>The basics</h3>
              <ul style={{ paddingLeft: 18, margin: 0, color: "var(--ink-2)", display: "flex", flexDirection: "column", gap: 8 }}>
                <li>Comfortable in at least one of: JavaScript / TypeScript, Angular, React, or .NET / C#.</li>
                <li>You can read existing code and ask the right questions.</li>
                <li>You write clean, readable code — and clear commit messages.</li>
                <li>You communicate proactively, especially when stuck.</li>
                <li>You're available on weekdays, on time, every day.</li>
              </ul>
            </div>

            <div className="reveal" data-delay="2">
              <div className="eyebrow" style={{ marginBottom: 18 }}>Bonus</div>
              <h3 style={{ fontSize: 28, color: "var(--ink)", letterSpacing: "-0.02em", marginBottom: 16 }}>Nice to have</h3>
              <ul style={{ paddingLeft: 18, margin: 0, color: "var(--ink-2)", display: "flex", flexDirection: "column", gap: 8 }}>
                <li>A side project, GitHub profile, or college project you can walk us through.</li>
                <li>Familiarity with Git, branching, and pull requests.</li>
                <li>Exposure to SQL (we use MS SQL Server).</li>
                <li>Curiosity about the print and manufacturing industry.</li>
                <li>Bias toward shipping over over-engineering.</li>
              </ul>
            </div>
          </div>

          <style>{`
            @media (max-width: 900px) {
              .opp-look-grid { grid-template-columns: 1fr !important; }
            }
          `}</style>
        </div>
      </section>

      {/* APPLY FORM */}
      <section className="section" id="apply">
        <div className="container">
          <SectionHead
            eyebrow="Apply"
            title="Send us your details."
            sub="Fill the form below. We'll route your details to hr@printbala.com and get back within 3–5 working days."
          />

          <div
            className="reveal"
            style={{
              maxWidth: 720,
              margin: "0 auto",
              background: "var(--bg-elev)",
              border: "1px solid var(--line)",
              borderRadius: "var(--radius-lg)",
              padding: "clamp(28px, 4vw, 44px)",
            }}
          >
            {!sent ? (
              <form onSubmit={onSubmit} className="opp-form" noValidate>
                <div className="opp-row two">
                  <Field
                    label="First name"
                    required
                    value={data.firstName}
                    onChange={(v) => update("firstName", v)}
                    invalid={touched && !data.firstName.trim()}
                    placeholder="Aarav"
                  />
                  <Field
                    label="Last name"
                    required
                    value={data.lastName}
                    onChange={(v) => update("lastName", v)}
                    invalid={touched && !data.lastName.trim()}
                    placeholder="Sharma"
                  />
                </div>

                <div className="opp-row two">
                  <Field
                    label="Email"
                    type="email"
                    required
                    value={data.email}
                    onChange={(v) => update("email", v)}
                    invalid={touched && !/^\S+@\S+\.\S+$/.test(data.email)}
                    placeholder="aarav@example.com"
                  />
                  <Field
                    label="Mobile"
                    type="tel"
                    required
                    value={data.mobile}
                    onChange={(v) => update("mobile", v)}
                    invalid={touched && data.mobile.trim().length < 7}
                    placeholder="+91 98xxxxxxxx"
                  />
                </div>

                <Field
                  label="Address"
                  required
                  textarea
                  value={data.address}
                  onChange={(v) => update("address", v)}
                  invalid={touched && !data.address.trim()}
                  placeholder="City, State, PIN"
                />

                <p
                  style={{
                    fontSize: 13,
                    color: "var(--ink-3)",
                    marginTop: 4,
                    marginBottom: 0,
                    lineHeight: 1.5,
                  }}
                >
                  By submitting, you confirm you can commit 4–5 hours daily and join the daily standup. Your details are sent directly to PrintBala HR.
                </p>

                <div style={{ display: "flex", gap: 12, marginTop: 8, flexWrap: "wrap", alignItems: "center" }}>
                  <button
                    type="submit"
                    className="btn btn-primary"
                    disabled={sending}
                    style={{ opacity: isFilled && !sending ? 1 : 0.55, cursor: sending ? "wait" : "pointer" }}
                  >
                    {sending ? "Sending…" : "Submit application"}
                    {!sending && (
                      <svg className="arrow" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                        <path d="M5 12h14M13 5l7 7-7 7" />
                      </svg>
                    )}
                  </button>
                  <button
                    type="button"
                    className="btn btn-ghost"
                    disabled={sending}
                    onClick={() => {
                      setData({ firstName: "", lastName: "", email: "", mobile: "", address: "" });
                      setTouched(false);
                      setError("");
                    }}
                  >
                    Clear
                  </button>
                </div>

                {touched && !isFilled && (
                  <div
                    style={{
                      marginTop: 4,
                      color: "#b3261e",
                      fontSize: 13,
                      fontFamily: "var(--font-mono)",
                    }}
                  >
                    Please complete all fields with valid information.
                  </div>
                )}

                {error && (
                  <div
                    style={{
                      marginTop: 4,
                      color: "#b3261e",
                      fontSize: 13,
                      fontFamily: "var(--font-body)",
                      lineHeight: 1.5,
                    }}
                  >
                    {error}
                  </div>
                )}
              </form>
            ) : (
              <div style={{ textAlign: "center", padding: "20px 8px" }}>
                <div
                  style={{
                    width: 64,
                    height: 64,
                    borderRadius: "50%",
                    background: "var(--accent-soft)",
                    color: "var(--accent-deep)",
                    display: "grid",
                    placeItems: "center",
                    margin: "0 auto 20px",
                  }}
                >
                  <svg viewBox="0 0 24 24" width="30" height="30" fill="none" stroke="currentColor" strokeWidth="2.2">
                    <path d="M4 12l5 5L20 7" />
                  </svg>
                </div>
                <h3 style={{ fontSize: 26, color: "var(--ink)", letterSpacing: "-0.02em", margin: "0 0 10px" }}>
                  Application submitted.
                </h3>
                <p style={{ color: "var(--ink-3)", maxWidth: 520, margin: "0 auto 24px" }}>
                  Thanks — your details are with PrintBala HR. We review every application and will get back within 3–5 working days at the email you provided.
                </p>
                <div style={{ display: "flex", gap: 10, justifyContent: "center", flexWrap: "wrap" }}>
                  <button
                    className="btn btn-ghost"
                    onClick={() => {
                      setSent(false);
                      setData({ firstName: "", lastName: "", email: "", mobile: "", address: "" });
                      setTouched(false);
                      setError("");
                    }}
                  >
                    Submit another
                  </button>
                  <button className="btn btn-primary" onClick={() => setRoute && setRoute("home")}>
                    Back to home
                  </button>
                </div>
              </div>
            )}
          </div>

          <style>{`
            .opp-form { display: flex; flex-direction: column; gap: 18px; }
            .opp-row.two { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
            .opp-field { display: flex; flex-direction: column; gap: 6px; }
            .opp-field label {
              font-family: var(--font-mono);
              font-size: 11px;
              letter-spacing: 0.18em;
              text-transform: uppercase;
              color: var(--ink-3);
            }
            .opp-field label .req { color: var(--accent); margin-left: 2px; }
            .opp-field input,
            .opp-field textarea {
              width: 100%;
              background: var(--bg);
              border: 1px solid var(--line-strong);
              border-radius: var(--radius-md);
              padding: 14px 16px;
              font-family: var(--font-body);
              font-size: 16px;
              color: var(--ink);
              outline: none;
              transition: border-color 160ms var(--ease-out), box-shadow 160ms var(--ease-out);
            }
            .opp-field textarea { resize: vertical; min-height: 96px; font-family: var(--font-body); }
            .opp-field input:focus,
            .opp-field textarea:focus {
              border-color: var(--accent);
              box-shadow: 0 0 0 3px color-mix(in oklch, var(--accent) 18%, transparent);
            }
            .opp-field.invalid input,
            .opp-field.invalid textarea { border-color: #b3261e; }
            @media (max-width: 700px) {
              .opp-row.two { grid-template-columns: 1fr; }
            }
          `}</style>
        </div>
      </section>
    </main>
  );
}

function Field({ label, value, onChange, required, type = "text", placeholder, invalid, textarea }) {
  return (
    <div className={`opp-field ${invalid ? "invalid" : ""}`}>
      <label>
        {label}{required && <span className="req">*</span>}
      </label>
      {textarea ? (
        <textarea
          value={value}
          onChange={(e) => onChange(e.target.value)}
          placeholder={placeholder}
          rows={3}
        />
      ) : (
        <input
          type={type}
          value={value}
          onChange={(e) => onChange(e.target.value)}
          placeholder={placeholder}
          autoComplete="off"
        />
      )}
    </div>
  );
}
