// Record detail view for a single Shipping Method
const { useState: useStateRD } = React;

const RecordDetail = ({ record, onBack, onEdit, onDelete, onUpdate }) => {
  const [tab, setTab] = useState("Overview");
  const [moreOpen, setMoreOpen] = useState(false);
  const u = USERS[record.updatedBy] || { name: record.updatedBy, color: "#A3ACBA" };

  return (
    <div style={{ background: "#fff", border: "1px solid var(--mw-border)", borderRadius: 16, overflow: "hidden", boxShadow: "var(--mw-shadow-card)" }}>
      {/* Breadcrumb */}
      <div style={{ display: "flex", alignItems: "center", padding: "10px 16px", gap: 8, fontSize: 12, color: "var(--mw-text-tertiary)", borderBottom: "1px solid var(--mw-border-soft)" }}>
        <button onClick={onBack} style={{ border: 0, background: "transparent", padding: 0, color: "var(--mw-text-tertiary)", cursor: "pointer", fontFamily: "inherit", fontSize: 12 }}>Shipping Methods</button>
        <img src="assets/icons/chevronRight.svg" style={{ width: 10, height: 10, opacity: 0.5 }} />
        <span style={{ color: "var(--mw-text-primary)" }}>{record.name}</span>
        <div style={{ marginLeft: "auto", display: "flex", gap: 6 }}>
          <Button size="sm" kind="ghost" icon="pen" onClick={onEdit}>Edit</Button>
          <Button size="sm" kind="ghost" icon="archive" onClick={() => onUpdate({ active: !record.active })}>{record.active ? "Deactivate" : "Activate"}</Button>
          <div style={{ position: "relative" }}>
            <Button size="sm" kind="ghost" icon="more" onClick={() => setMoreOpen(o => !o)}>More</Button>
            {moreOpen && (
              <>
                <div onClick={() => setMoreOpen(false)} style={{ position: "fixed", inset: 0, zIndex: 20 }} />
                <div style={{ position: "absolute", top: "calc(100% + 4px)", right: 0, minWidth: 180, background: "#fff", border: "1px solid var(--mw-border)", borderRadius: 10, boxShadow: "var(--mw-shadow-popover, 0 8px 24px rgba(15,18,32,.12))", padding: 4, zIndex: 30 }}>
                  <button onClick={() => setMoreOpen(false)} style={{ display: "flex", alignItems: "center", gap: 10, width: "100%", padding: "8px 10px", border: 0, background: "transparent", borderRadius: 6, cursor: "pointer", fontFamily: "inherit", fontSize: 13, color: "var(--mw-text-primary)", textAlign: "left" }}
                    onMouseEnter={e => e.currentTarget.style.background = "var(--mw-bg)"}
                    onMouseLeave={e => e.currentTarget.style.background = "transparent"}>
                    <img src="assets/icons/files.svg" style={{ width: 14, height: 14, opacity: 0.7 }} />
                    Clone Method
                  </button>
                </div>
              </>
            )}
          </div>
        </div>
      </div>

      {/* Stage / hero */}
      <div style={{ padding: "24px 28px", display: "flex", gap: 20, alignItems: "flex-start", borderBottom: "1px solid var(--mw-border-soft)", background: "linear-gradient(135deg, rgba(232,233,246,.35), rgba(255,177,99,.06) 60%, transparent)" }}>
        <TypeEmblem type={record.type} size={56} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
            <h1 style={{ fontSize: 24, fontWeight: 700, letterSpacing: "-0.015em" }}>{record.name}</h1>
            {record.isDefault && <Chip tone="indigoSoft" size="md" dot>Default Method</Chip>}
            {!record.active && <Chip tone="neutral" size="md">Inactive</Chip>}
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 14, marginTop: 6, fontSize: 13, color: "var(--mw-text-tertiary)", flexWrap: "wrap" }}>
            <span style={{ fontFamily: "var(--mw-font-mono)" }}>{record.code}</span>
            <span style={{ width: 3, height: 3, borderRadius: 99, background: "var(--mw-text-quaternary)" }} />
            <span>{record.type}</span>
            {record.carrier && <>
              <span style={{ width: 3, height: 3, borderRadius: 99, background: "var(--mw-text-quaternary)" }} />
              <span>{record.carrier}</span>
            </>}
            {record.transit > 0 && <>
              <span style={{ width: 3, height: 3, borderRadius: 99, background: "var(--mw-text-quaternary)" }} />
              <span>{record.transit} {record.transit === 1 ? "day transit" : "days transit"}</span>
            </>}
          </div>
          {record.description && <p style={{ marginTop: 12, fontSize: 14, color: "var(--mw-text-secondary)", lineHeight: 1.5, maxWidth: 720 }}>{record.description}</p>}
        </div>
        <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 10 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <span style={{ fontSize: 12, color: "var(--mw-text-tertiary)" }}>{record.active ? "Active" : "Inactive"}</span>
            <Toggle checked={record.active} onChange={v => onUpdate({ active: v })} />
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <span style={{ fontSize: 12, color: "var(--mw-text-tertiary)" }}>Default</span>
            <Toggle checked={record.isDefault} onChange={v => onUpdate({ isDefault: v })} />
          </div>
        </div>
      </div>

      {/* Tabs */}
      <div style={{ display: "flex", padding: "0 16px", borderBottom: "1px solid var(--mw-border-soft)", gap: 2 }}>
        {["Overview", "Pricing & Behavior", "Availability", "Activity"].map(t => (
          <button key={t} onClick={() => setTab(t)} style={{
            padding: "10px 14px", border: 0, background: "transparent", cursor: "pointer", fontFamily: "inherit",
            fontSize: 13, fontWeight: 500, position: "relative",
            color: tab === t ? "var(--mw-text-primary)" : "var(--mw-text-tertiary)",
            borderBottom: tab === t ? "2px solid var(--mw-brand-500)" : "2px solid transparent",
            marginBottom: -1
          }}>{t}</button>
        ))}
      </div>

      {/* Tab body */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 320px", minHeight: 380 }}>
        <div style={{ padding: "20px 24px", borderRight: "1px solid var(--mw-border-soft)" }}>
          {tab === "Overview" && <OverviewTab record={record} />}
          {tab === "Pricing & Behavior" && <PricingTab record={record} />}
          {tab === "Availability" && <AvailabilityTab record={record} />}
          {tab === "Activity" && <ActivityTab record={record} />}
        </div>
        <SidePanel record={record} u={u} />
      </div>
    </div>
  );
};

const Stat = ({ label, value, tone, hint, mono }) => (
  <div style={{ padding: "12px 14px", background: "#fff", border: "1px solid var(--mw-border)", borderRadius: 12, display: "flex", flexDirection: "column", gap: 4, minWidth: 0 }}>
    <div style={{ fontSize: 11, fontWeight: 500, color: "var(--mw-text-tertiary)", textTransform: "uppercase", letterSpacing: ".04em" }}>{label}</div>
    <div style={{ fontSize: 16, fontWeight: 600, color: tone || "var(--mw-text-primary)", fontFamily: mono ? "var(--mw-font-mono)" : "inherit", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{value}</div>
    {hint && <div style={{ fontSize: 11, color: "var(--mw-text-tertiary)" }}>{hint}</div>}
  </div>
);

const OverviewTab = ({ record }) => (
  <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 10 }}>
      <Stat label="Pricing" value={record.pricing === "Flat Rate" ? `$${record.flat.toFixed(2)}` : record.pricing} hint={record.pricing === "Flat Rate" ? "Per order" : ""} />
      <Stat label="Transit Time" value={record.transit > 0 ? `${record.transit} ${record.transit === 1 ? "day" : "days"}` : "—"} hint="Estimated" />
      <Stat label="Carrier" value={record.carrier || "—"} hint={record.trackingEnabled ? "Tracking enabled" : "No tracking"} />
    </div>

    <div>
      <SectionHeader>Details</SectionHeader>
      <div style={{ border: "1px solid var(--mw-border)", borderRadius: 12, background: "#fff", padding: "14px 16px", display: "grid", gridTemplateColumns: "1fr 1fr", rowGap: 12, columnGap: 20 }}>
        <DetailRow label="Code" value={<span style={{ fontFamily: "var(--mw-font-mono)" }}>{record.code}</span>} />
        <DetailRow label="Type" value={record.type} />
        <DetailRow label="Carrier" value={record.carrier || "—"} />
        <DetailRow label="Pricing" value={record.pricing === "Flat Rate" ? `$${record.flat.toFixed(2)} flat` : record.pricing} />
        <DetailRow label="Transit" value={record.transit > 0 ? `${record.transit} ${record.transit === 1 ? "day" : "days"}` : "—"} />
        <DetailRow label="Ownership" value={record.ownership} />
      </div>
    </div>

    <div>
      <SectionHeader>Ownership</SectionHeader>
      <div style={{ padding: "14px 16px", border: "1px solid var(--mw-border)", borderRadius: 12, background: "#fff", display: "flex", alignItems: "center", gap: 12 }}>
        <div style={{ width: 32, height: 32, borderRadius: 8, background: "var(--mw-brand-50)", display: "inline-flex", alignItems: "center", justifyContent: "center" }}>
          <img src="assets/icons/branch.svg" style={{ width: 16, height: 16, opacity: 0.7 }} />
        </div>
        <div>
          <div style={{ fontSize: 14, fontWeight: 500 }}>Title transfers {record.ownership === "When Shipped" ? "when shipped" : record.ownership === "When Delivered" ? "when delivered" : "manually"}</div>
          <div style={{ fontSize: 12, color: "var(--mw-text-tertiary)" }}>
            {record.ownership === "When Shipped" && "Customer takes ownership the moment we hand the goods to the carrier."}
            {record.ownership === "When Delivered" && "Ownership transfers only after delivery is confirmed."}
            {record.ownership === "Manual / Custom" && "Ownership transfer is set manually by ops on each order."}
          </div>
        </div>
      </div>
    </div>
  </div>
);

const BehaviorRow = ({ label, value, description, last }) => (
  <li style={{ display: "flex", alignItems: "center", gap: 12, padding: "12px 16px", borderBottom: last ? 0 : "1px solid var(--mw-border-soft)" }}>
    <div style={{ width: 24, height: 24, borderRadius: 99, background: value ? "rgba(34,134,58,.1)" : "var(--mw-bg)", display: "inline-flex", alignItems: "center", justifyContent: "center" }}>
      <img src={`assets/icons/${value ? "check" : "cross"}.svg`} style={{ width: 12, height: 12, filter: value ? "invert(40%) sepia(94%) saturate(388%) hue-rotate(94deg) brightness(95%)" : "none", opacity: value ? 1 : 0.4 }} />
    </div>
    <div style={{ flex: 1 }}>
      <div style={{ fontSize: 14, fontWeight: 500 }}>{label}</div>
      <div style={{ fontSize: 12, color: "var(--mw-text-tertiary)" }}>{description}</div>
    </div>
    <span style={{ fontSize: 12, fontWeight: 500, color: value ? "var(--mw-success)" : "var(--mw-text-tertiary)" }}>{value ? "Enabled" : "Off"}</span>
  </li>
);

const PricingTab = ({ record }) => (
  <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
      <Stat label="Pricing Method" value={record.pricing} />
      {record.pricing === "Flat Rate"
        ? <Stat label="Flat Amount" value={`$${record.flat.toFixed(2)}`} hint="Per order, USD" />
        : <Stat label="How It's Priced" value={record.pricing === "Free Shipping" ? "Customer is not charged" : "Quoted manually by ops"} />
      }
    </div>
    {record.pricing === "Manual" && (
      <div>
        <SectionHeader>Amount entry workflow</SectionHeader>
        <div style={{ border: "1px solid var(--mw-border)", borderRadius: 12, background: "#fff", padding: "14px 16px" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 12 }}>
            <div style={{ width: 32, height: 32, borderRadius: 8, background: "var(--mw-brand-50)", display: "inline-flex", alignItems: "center", justifyContent: "center" }}>
              <img src="assets/icons/clock.svg" style={{ width: 16, height: 16, opacity: 0.7 }} />
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 14, fontWeight: 500 }}>Entered at: {record.amountEntryPoint || "Shipment"}</div>
              <div style={{ fontSize: 12, color: "var(--mw-text-tertiary)" }}>
                Users will be prompted to enter the shipping amount at this step.
              </div>
            </div>
          </div>
          <ul style={{ margin: 0, padding: 0, listStyle: "none", borderTop: "1px solid var(--mw-border-soft)" }}>
            <BehaviorRow label="Require Amount Before Continuing" value={!!record.requireAmountBeforeContinuing} description={`Block progress past ${record.amountEntryPoint || "Shipment"} until amount is entered.`} />
            <BehaviorRow label="Allow Amount Override" value={record.allowAmountOverride !== false} description="Authorized users can modify the shipping charge later." last />
          </ul>
        </div>
      </div>
    )}
    <div>
      <SectionHeader>Recent quotes using this method</SectionHeader>
      <div style={{ border: "1px solid var(--mw-border)", borderRadius: 12, background: "#fff", overflow: "hidden" }}>
        {[
          { id: "Q-982510", customer: "Crestwood Robotics", weight: "12 lbs", amount: record.pricing === "Flat Rate" ? `$${record.flat.toFixed(2)}` : "$48.00", date: "11/04/2025" },
          { id: "Q-982502", customer: "Northstar Manufacturing", weight: "47 lbs", amount: record.pricing === "Flat Rate" ? `$${record.flat.toFixed(2)}` : "$112.50", date: "11/02/2025" },
          { id: "Q-982488", customer: "Vector Steel Works", weight: "8 lbs", amount: record.pricing === "Flat Rate" ? `$${record.flat.toFixed(2)}` : "$22.00", date: "10/28/2025" },
        ].map((q, i, arr) => (
          <div key={q.id} style={{ display: "grid", gridTemplateColumns: "1fr 1.6fr 0.8fr 0.8fr 0.8fr", padding: "10px 14px", borderBottom: i === arr.length - 1 ? 0 : "1px solid var(--mw-border-soft)", fontSize: 13, alignItems: "center" }}>
            <span style={{ color: "var(--mw-brand-500)", fontFamily: "var(--mw-font-mono)" }}>{q.id}</span>
            <span style={{ color: "var(--mw-text-secondary)" }}>{q.customer}</span>
            <span style={{ color: "var(--mw-text-tertiary)" }}>{q.weight}</span>
            <span style={{ color: "var(--mw-text-primary)", fontWeight: 500 }}>{q.amount}</span>
            <span style={{ color: "var(--mw-text-tertiary)", textAlign: "right", fontSize: 12 }}>{q.date}</span>
          </div>
        ))}
      </div>
    </div>
  </div>
);

const AvailabilityTab = ({ record }) => (
  <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
    <AvailRow title="Warehouses" items={record.warehouses} all="All warehouses" icon="layers" />
    <AvailRow title="Countries" items={record.countries} all="All countries" icon="branch" />
    <AvailRow title="Customers" items={[]} all="All customers" icon="user" />
  </div>
);

const AvailRow = ({ title, items, all, icon }) => (
  <div style={{ border: "1px solid var(--mw-border)", borderRadius: 12, background: "#fff", padding: "14px 16px" }}>
    <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: items.length ? 12 : 0 }}>
      <div style={{ width: 28, height: 28, borderRadius: 8, background: "var(--mw-bg)", display: "inline-flex", alignItems: "center", justifyContent: "center" }}>
        <img src={`assets/icons/${icon}.svg`} style={{ width: 14, height: 14, opacity: 0.6 }} />
      </div>
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 14, fontWeight: 500 }}>{title}</div>
        {items.length === 0 && <div style={{ fontSize: 12, color: "var(--mw-text-tertiary)" }}>{all}</div>}
      </div>
      <span style={{ fontSize: 12, color: "var(--mw-text-tertiary)" }}>{items.length || "All"}</span>
    </div>
    {items.length > 0 && (
      <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
        {items.map(x => <Chip key={x} tone="neutral">{x}</Chip>)}
      </div>
    )}
  </div>
);

const ActivityTab = ({ record }) => {
  const events = [
    { who: "EC", what: "updated Flat Shipping Amount", when: "11/04/2025 | 3:43 pm", detail: record.pricing === "Flat Rate" ? `$10.99 → $${record.flat.toFixed(2)}` : null },
    { who: "RF", what: "set as Default Method", when: "10/22/2025 | 9:12 am", detail: record.isDefault ? "Default Method enabled" : null },
    { who: "RF", what: "created this Shipping Method", when: "10/14/2025 | 4:10 pm" },
  ];
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 0, position: "relative" }}>
      {events.map((e, i) => {
        const u = USERS[e.who] || { name: e.who, color: "#A3ACBA" };
        return (
          <div key={i} style={{ display: "flex", gap: 12, paddingBottom: 16, position: "relative" }}>
            <div style={{ display: "flex", flexDirection: "column", alignItems: "center", paddingTop: 4 }}>
              <Avatar size={28} initials={e.who} color={u.color} />
              {i < events.length - 1 && <div style={{ flex: 1, width: 1, background: "var(--mw-border-soft)", marginTop: 4 }} />}
            </div>
            <div style={{ flex: 1, paddingBottom: 4 }}>
              <div style={{ fontSize: 13 }}>
                <span style={{ fontWeight: 500 }}>{u.name}</span>
                <span style={{ color: "var(--mw-text-tertiary)" }}> {e.what}</span>
              </div>
              {e.detail && <div style={{ fontSize: 12, color: "var(--mw-text-tertiary)", marginTop: 4, padding: "8px 10px", background: "var(--mw-bg)", border: "1px solid var(--mw-border-soft)", borderRadius: 8, fontFamily: "var(--mw-font-mono)", display: "inline-block" }}>{e.detail}</div>}
              <div style={{ fontSize: 11, color: "var(--mw-text-tertiary)", marginTop: 4 }}>{e.when}</div>
            </div>
          </div>
        );
      })}
    </div>
  );
};

const SectionHeader = ({ children }) => (
  <div style={{ fontSize: 11, fontWeight: 600, color: "var(--mw-text-tertiary)", textTransform: "uppercase", letterSpacing: ".06em", marginBottom: 8 }}>{children}</div>
);

const SidePanel = ({ record, u }) => (
  <aside style={{ padding: "20px 20px", display: "flex", flexDirection: "column", gap: 18, background: "#fff" }}>
    <div>
      <SectionHeader>Behavior</SectionHeader>
      <ul style={{ margin: 0, padding: 0, listStyle: "none", border: "1px solid var(--mw-border)", borderRadius: 12, background: "#fff" }}>
        <BehaviorRow label="Customer Visible" value={record.customerVisible} description="Shown on the storefront and in customer-facing quotes." />
        <BehaviorRow label="Tracking Enabled" value={record.trackingEnabled} description="Ops can attach tracking numbers." />
        <BehaviorRow label="Requires Signature" value={record.signature} description="Carrier collects signature on delivery." />
        <BehaviorRow label="Default Method" value={record.isDefault} description="Used when no method is selected." last />
      </ul>
    </div>
    <div>
      <SectionHeader>Last updated</SectionHeader>
      <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "10px 12px", border: "1px solid var(--mw-border-soft)", borderRadius: 10, background: "var(--mw-bg)" }}>
        <Avatar size={28} initials={record.updatedBy} color={u.color} />
        <div style={{ minWidth: 0 }}>
          <div style={{ fontSize: 13, fontWeight: 500, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{u.name}</div>
          <div style={{ fontSize: 11, color: "var(--mw-text-tertiary)" }}>{record.updated} | 3:43 pm</div>
        </div>
      </div>
    </div>
  </aside>
);

const DetailRow = ({ label, value }) => (
  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 8 }}>
    <span style={{ fontSize: 12, color: "var(--mw-text-tertiary)" }}>{label}</span>
    <span style={{ fontSize: 13, color: "var(--mw-text-primary)", textAlign: "right" }}>{value}</span>
  </div>
);

const SideAction = ({ icon, children }) => (
  <button style={{
    display: "flex", alignItems: "center", gap: 10, padding: "8px 10px", border: 0, background: "transparent",
    borderRadius: 8, cursor: "pointer", fontFamily: "inherit", fontSize: 13, color: "var(--mw-text-secondary)", textAlign: "left",
    transition: "background 120ms"
  }}
  onMouseEnter={e => e.currentTarget.style.background = "var(--mw-bg)"}
  onMouseLeave={e => e.currentTarget.style.background = "transparent"}>
    <img src={`assets/icons/${icon}.svg`} style={{ width: 14, height: 14, opacity: 0.6 }} />
    {children}
  </button>
);

window.RecordDetail = RecordDetail;
