// Information — Scope 2 (fees) + Scope 3 (W-9 secure document), Draft 3.
// Fees support per-IC custom overrides; both display states are shown via the
// view toggle (in production the schedule resolves automatically from the IC's account).
//
// NOTE: custom override amounts below are SAMPLE values to demonstrate the
// "custom rate" display state — replace with real per-IC data when available.

// Offline seed / fallback. In production the "Default schedule" base rates load
// from the proxied Fee Schedule sheet (src=fees, columns: Service | Description |
// Unit | Base Rate); this array is the seed shown until live rows arrive and the
// fallback if the source is unconfigured/unreachable. The `custom` amounts here
// are SAMPLE per-IC override values — that "My rates" path is a separate build.
const FEE_SCHEDULE = [
  { id: "overnight", icon: "moon",  name: "Overnight Service Fee", desc: "Applied when an assignment requires an overnight stay away from your home base.", unit: "per night",  std: "$185", custom: "$160" },
  { id: "flight",    icon: "plane", name: "Flight Booking Fee",    desc: "Per-ticket service fee for air travel booked through the RDB crew travel desk.", unit: "per ticket", std: "$45",  custom: "$30"  },
];

// Map a Fee Schedule sheet (row 1 headers, row 2 down) to the FeeRow shape.
// Service → name, Description → desc, Unit → unit, Base Rate → std (the dollar
// amount). The sheet carries base rates only; icon + the sample `custom` override
// are matched back from the seed by service name (the "My rates" path is untouched).
function buildFees(text) {
  const slug = s => (s || "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
  const { rows } = rdbParseSheetObjects(text);
  return rows
    .map(r => {
      const name = (r["Service"] || "").trim();
      if (!name) return null;
      const seed = FEE_SCHEDULE.find(s => s.name.toLowerCase() === name.toLowerCase());
      const rate = (r["Base Rate"] || "").trim();
      const std = rate ? (rate[0] === "$" ? rate : "$" + rate) : (seed ? seed.std : "");
      return {
        id: seed ? seed.id : slug(name) || name,
        icon: seed ? seed.icon : "dollar-sign",
        name,
        desc: (r["Description"] || "").trim() || (seed ? seed.desc : ""),
        unit: (r["Unit"] || "").trim() || (seed ? seed.unit : ""),
        std,
        custom: seed ? seed.custom : null,
      };
    })
    .filter(Boolean);
}

// "Default schedule" base rates — live from the proxied sheet, seeded by FEE_SCHEDULE.
function useFees() {
  return useSheet(apiUrl("fees"), FEE_SCHEDULE, buildFees);
}

function FeeRow({ f, custom }) {
  const overridden = custom && f.custom && f.custom !== f.std;
  return (
    <div style={{ position: "relative", display: "grid", gridTemplateColumns: "44px 1fr auto", gap: 18, alignItems: "center", padding: "22px 24px", borderBottom: "1px solid var(--ink-2)" }}>
      <div style={{ width: 44, height: 44, border: "1px solid var(--ink-4)", display: "flex", alignItems: "center", justifyContent: "center" }}>
        <Icon name={f.icon} size={20} color="var(--rdb-gold)" />
      </div>
      <div style={{ minWidth: 0 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 5 }}>
          <span style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 17, color: "var(--fg-1)", letterSpacing: "-0.01em" }}>{f.name}</span>
          {overridden && <Chip tone="gold" dot={false}>Custom rate</Chip>}
        </div>
        <p style={{ fontFamily: "var(--font-body)", fontSize: 13, lineHeight: 1.5, color: "var(--fg-3)", margin: 0, maxWidth: 520 }}>{f.desc}</p>
      </div>
      <div style={{ textAlign: "right", whiteSpace: "nowrap" }}>
        {overridden && (
          <span style={{ fontFamily: "var(--font-mono)", fontSize: 13, color: "var(--ink-6)", textDecoration: "line-through", marginRight: 10 }}>{f.std}</span>
        )}
        <span style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 24, letterSpacing: "-0.02em", color: overridden ? "var(--rdb-gold)" : "var(--fg-1)" }}>{overridden ? f.custom : f.std}</span>
        <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--ink-6)", marginLeft: 8 }}>{f.unit}</span>
      </div>
    </div>
  );
}

// View toggle — Default schedule vs. the logged-in IC's custom schedule.
function FeeViewToggle({ custom, onChange, name }) {
  const opt = (val, label) => {
    const active = custom === val;
    return (
      <button onClick={() => onChange(val)} style={{
        padding: "8px 16px", border: "none", cursor: "pointer",
        background: active ? "var(--rdb-gold)" : "transparent",
        color: active ? "#0D0D0D" : "var(--fg-2)",
        fontFamily: "var(--font-body)", fontWeight: 600, fontSize: 11, letterSpacing: "0.08em",
        transition: "all 160ms cubic-bezier(.22,1,.36,1)",
      }}>{label}</button>
    );
  };
  return (
    <div style={{ display: "inline-flex", border: "1px solid var(--ink-3)" }}>
      {opt(false, "Default schedule")}
      {opt(true, name ? "My rates · " + name : "My rates")}
    </div>
  );
}

// W-9 — Scope 3 secure document card.
function W9Card() {
  const [hover, setHover] = React.useState(false);
  return (
    <div style={{ border: "1px solid var(--rdb-gold)", background: "var(--ink-0)", padding: "26px 26px 22px", display: "flex", flexDirection: "column", gap: 18 }}>
      <div style={{ display: "flex", alignItems: "flex-start", gap: 16 }}>
        <div style={{ width: 48, height: 48, border: "1px solid var(--rdb-gold)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0, background: "var(--rdb-gold-faint)" }}>
          <Icon name="lock" size={22} color="var(--rdb-gold)" />
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontFamily: "var(--font-body)", fontWeight: 600, fontSize: 10, letterSpacing: "0.28em", color: "var(--rdb-gold)", textTransform: "uppercase", marginBottom: 7 }}>Secure Document</div>
          <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 19, color: "var(--fg-1)", letterSpacing: "-0.01em", lineHeight: 1.2 }}>RDB W-9</div>
          <div style={{ fontFamily: "var(--font-body)", fontSize: 13, color: "var(--fg-3)", marginTop: 5 }}>Request for Taxpayer Identification Number &amp; Certification</div>
        </div>
      </div>

      <p style={{ fontFamily: "var(--font-body)", fontSize: 13, lineHeight: 1.55, color: "var(--fg-2)", margin: 0 }}>
        RDB's completed W-9, available for your records and to share with your accountant.
      </p>

      <a
        href={(window.__resources && window.__resources.w9) || "assets/W9-RDB-2026.pdf"}
        target="_blank" rel="noopener noreferrer" download="W9-RDB-2026.pdf"
        onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
        style={{
          display: "flex", alignItems: "center", justifyContent: "center", gap: 10,
          padding: "13px 18px", cursor: "pointer", textDecoration: "none",
          background: hover ? "var(--rdb-gold-bright)" : "var(--rdb-gold)",
          color: "#0D0D0D", fontFamily: "var(--font-body)", fontWeight: 600, fontSize: 13,
          letterSpacing: "0.04em", transition: "background 160ms",
        }}>
        <Icon name="download" size={16} color="#0D0D0D" />
        Download W-9 · PDF
      </a>

      <div style={{ display: "flex", alignItems: "center", gap: 9, borderTop: "1px solid var(--ink-3)", paddingTop: 14 }}>
        <Icon name="shield-check" size={15} color="var(--success)" />
        <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--fg-2)", letterSpacing: "0.01em" }}>No banking information included.</span>
      </div>
    </div>
  );
}

function InformationPage({ user }) {
  const [custom, setCustom] = React.useState(false);
  const { rows: feeRows } = useFees();
  const firstName = user && user.name ? user.name.split(" ")[0] : "You";

  return (
    <div style={{ padding: "48px 64px 96px", maxWidth: 1180, margin: "0 auto" }}>
      <div style={{ marginBottom: 12 }}>
        <div className="rdb-eyebrow" style={{ marginBottom: 14 }}>Backstage · Reference</div>
        <h1 style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 48, letterSpacing: "-0.02em", color: "var(--fg-1)", margin: 0, lineHeight: 1.02 }}>Fees &amp; Information</h1>
        <p style={{ fontFamily: "var(--font-body)", fontSize: 16, lineHeight: 1.6, color: "var(--fg-2)", margin: "16px 0 0", maxWidth: 620 }}>
          Service fees and key documents for independent contractors. Your schedule reflects any rates negotiated for your account.
        </p>
      </div>

      <div style={{ height: 1, background: "var(--rdb-gold-soft)", margin: "36px 0 36px" }} />

      <div className="rdb-info-grid" style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr", gap: 48, alignItems: "start" }}>
        {/* Fees */}
        <div>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 16, marginBottom: 18, flexWrap: "wrap" }}>
            <h2 style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 22, color: "var(--fg-1)", margin: 0, letterSpacing: "-0.01em" }}>Fee Schedule</h2>
            <FeeViewToggle custom={custom} onChange={setCustom} name={firstName} />
          </div>

          {custom && (
            <div style={{ display: "flex", alignItems: "center", gap: 12, border: "1px solid rgba(201,168,76,0.4)", background: "var(--rdb-gold-faint)", padding: "12px 16px", marginBottom: 16 }}>
              <Icon name="badge-check" size={16} color="var(--rdb-gold)" />
              <span style={{ fontFamily: "var(--font-body)", fontSize: 13, color: "var(--fg-2)" }}>
                Showing <span style={{ color: "var(--fg-1)", fontWeight: 600 }}>{firstName}'s</span> negotiated rates. Lines that differ from standard are marked <span style={{ color: "var(--rdb-gold)", fontWeight: 600 }}>Custom rate</span>.
              </span>
            </div>
          )}

          <div style={{ border: "1px solid var(--ink-3)" }}>
            {feeRows.map((f, i) => <FeeRow key={f.id} f={f} custom={custom} />)}
            <div style={{ padding: "13px 24px", background: "var(--ink-1)" }}>
              <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--ink-6)" }}>
                Fees are billed against assignments and reconciled on your statement. Questions → RDB Finance.
              </span>
            </div>
          </div>
        </div>

        {/* Documents */}
        <div>
          <h2 style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 22, color: "var(--fg-1)", margin: "0 0 18px", letterSpacing: "-0.01em" }}>Documents</h2>
          <W9Card />
        </div>
      </div>
    </div>
  );
}

// ---------- Mobile ----------
function MobileInformation({ user }) {
  const [custom, setCustom] = React.useState(false);
  const { rows: feeRows } = useFees();
  const firstName = user && user.name ? user.name.split(" ")[0] : "You";
  return (
    <div style={{ padding: "22px 18px 60px" }}>
      <div className="rdb-eyebrow" style={{ marginBottom: 10 }}>Backstage · Reference</div>
      <h1 style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 28, letterSpacing: "-0.02em", color: "var(--fg-1)", margin: "0 0 8px", lineHeight: 1.05 }}>Fees &amp; Information</h1>
      <p style={{ fontFamily: "var(--font-body)", fontSize: 14, lineHeight: 1.6, color: "var(--fg-2)", margin: "0 0 20px" }}>
        Service fees and key documents. Your schedule reflects rates negotiated for your account.
      </p>

      <div style={{ display: "flex", justifyContent: "center", marginBottom: 16 }}>
        <FeeViewToggle custom={custom} onChange={setCustom} name={firstName} />
      </div>

      <div style={{ border: "1px solid var(--ink-3)", marginBottom: 28 }}>
        {feeRows.map(f => {
          const overridden = custom && f.custom !== f.std;
          return (
            <div key={f.id} style={{ padding: "16px 16px", borderBottom: "1px solid var(--ink-2)" }}>
              <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 8 }}>
                <Icon name={f.icon} size={16} color="var(--rdb-gold)" />
                <span style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 15, color: "var(--fg-1)" }}>{f.name}</span>
                {overridden && <Chip tone="gold" dot={false}>Custom</Chip>}
              </div>
              <p style={{ fontFamily: "var(--font-body)", fontSize: 12, lineHeight: 1.5, color: "var(--fg-3)", margin: "0 0 10px" }}>{f.desc}</p>
              <div style={{ display: "flex", alignItems: "baseline", gap: 8 }}>
                {overridden && <span style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--ink-6)", textDecoration: "line-through" }}>{f.std}</span>}
                <span style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 20, color: overridden ? "var(--rdb-gold)" : "var(--fg-1)" }}>{overridden ? f.custom : f.std}</span>
                <span style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--ink-6)" }}>{f.unit}</span>
              </div>
            </div>
          );
        })}
      </div>

      <h2 style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 18, color: "var(--fg-1)", margin: "0 0 14px" }}>Documents</h2>
      <W9Card />
    </div>
  );
}

window.FEE_SCHEDULE = FEE_SCHEDULE;
Object.assign(window, { InformationPage, MobileInformation, W9Card, FeeViewToggle });
