/* GoogleBuilderForm — Google Wallet pass editor. Reuses the shared studio
   controls exported from the Apple studio's BuilderForm. */
const GBF = window.SpoonityWalletPassDesignSystem_de20b8;
const {
  StudioSection: Section, StudioFieldLabel: FieldLabel, StudioTwoCol: TwoCol,
  StudioSegmented: Segmented, StudioColorPicker: ColorPicker, StudioColorSwatches: ColorSwatches,
  StudioCropModal: CropModal, StudioImageUpload: ImageUpload,
  StudioRoleColorPicker: RoleColorPicker, StudioIconUpload: IconUpload,
  StudioPublishModal: PublishModal, studioEffectiveColors: effectiveColors,
  StudioGenerateDesignModal: GenerateDesignModal,
  StudioStoreLocations: StoreLocations,
  StudioThumbRemoveButton: ThumbRemoveButton,
} = window;

/* Platform indicator — Google active; Apple button opens the Apple studio. */
function GPlatformToggle({ onApple }) {
  const [hover, setHover] = React.useState(false);
  const cell = { width: 36, height: 30, borderRadius: 8, display: "flex", alignItems: "center", justifyContent: "center", boxSizing: "border-box" };
  return (
    <div style={{ display: "flex", gap: 6, alignItems: "center" }}>
      <button
        type="button" title="Design for Apple Wallet"
        onClick={() => onApple ? onApple() : window.open("../pass-studio/index.html", "_blank")}
        onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
        style={{
          ...cell, cursor: "pointer", transition: "background .15s ease, border-color .15s ease, opacity .15s ease",
          background: hover ? "var(--surface-secondary)" : "transparent",
          border: `1px solid ${hover ? "var(--border-primary)" : "transparent"}`,
          opacity: hover ? 1 : 0.55,
        }}
      >
        <img src="../../assets/apple-mark.svg" alt="Apple Wallet" style={{ height: 16 }} />
      </button>
      <div title="Google Wallet" style={{ ...cell, background: "var(--surface-secondary)", border: "1px solid var(--border-primary)" }}>
        <img src="../../assets/google-g.svg" alt="Google Wallet" style={{ height: 16 }} />
      </div>
    </div>
  );
}

/* Square logo uploader (Google requires a 660×660 logo, shown as a circle). */
function GLogoUpload({ src, onUpload, onClear }) {
  const inputRef = React.useRef(null);
  const [pending, setPending] = React.useState(null);
  const [dragging, setDragging] = React.useState(false);
  const [hover, setHover] = React.useState(false);
  const onFile = (e) => {
    const file = e.target.files && e.target.files[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = () => setPending(reader.result);
    reader.readAsDataURL(file);
    e.target.value = "";
  };
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
      <FieldLabel>Logo</FieldLabel>
      <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
        <div
          onMouseEnter={() => setHover(true)}
          onMouseLeave={() => setHover(false)}
          onDragOver={(e) => { e.preventDefault(); setDragging(true); }}
          onDragLeave={() => setDragging(false)}
          onDrop={(e) => { e.preventDefault(); setDragging(false); const file = e.dataTransfer.files[0]; if (!file) return; const reader = new FileReader(); reader.onload = () => setPending(reader.result); reader.readAsDataURL(file); }}
          style={{ position: "relative", width: 44, height: 44, flexShrink: 0, borderRadius: "50%", overflow: "hidden", border: dragging ? "2px dashed var(--border-focused, #1a73e8)" : "1px solid var(--border-primary)", background: "var(--surface-secondary)", display: "flex", alignItems: "center", justifyContent: "center" }}>
          {src ? <img src={src} alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }} /> : <span style={{ fontSize: 10, color: "var(--typography-tertiary)" }}>None</span>}
          {src && ThumbRemoveButton && <ThumbRemoveButton show={hover} onClear={onClear} title="Remove" />}
        </div>
        <div style={{ display: "flex", gap: 8 }}>
          <GBF.Button variant="tertiary" size="sm" onClick={() => inputRef.current && inputRef.current.click()}>{src ? "Replace" : "Upload image"}</GBF.Button>
        </div>
        <input ref={inputRef} type="file" accept="image/*" onChange={onFile} style={{ display: "none" }} />
      </div>
      {pending && (
        <CropModal src={pending} title="Crop logo" crops={{ w: 660, h: 660 }}
          onCancel={() => setPending(null)}
          onConfirm={(d) => { onUpload(d); setPending(null); }} />
      )}
    </div>
  );
}

function GoogleBuilderForm({ pass, setPass, accent = "#1a73e8", onApple, onUndo, onRedo, canUndo, canRedo }) {
  const set = (patch) => setPass({ ...pass, ...patch });
  const [publishing, setPublishing] = React.useState(false);
  const [generating, setGenerating] = React.useState(false);
  const [draftStatus, setDraftStatus] = React.useState("idle");
  const [shareUrl, setShareUrl] = React.useState(null);

  const handleSaveDraft = async () => {
    setDraftStatus("saving");
    try {
      const shareId = await window.saveDraftToSupabase(pass, "google");
      const url = `${location.origin}${location.pathname}?share=${shareId}`;
      setShareUrl(url);
      setDraftStatus("saved");
      setTimeout(() => setDraftStatus("idle"), 3000);
    } catch (e) {
      console.error("Save draft failed:", e);
      setDraftStatus("error");
      setTimeout(() => setDraftStatus("idle"), 3000);
    }
  };

  // Pin value/label colors to explicit hex so the preview and the JSON we send
  // the backend always agree.
  React.useEffect(() => {
    if (pass.foregroundColor && pass.labelColor) return;
    const eff = effectiveColors(pass);
    set({ foregroundColor: eff.foreground, labelColor: eff.label });
    // eslint-disable-next-line
  }, [pass.backgroundColor]);
  return (
    <div style={{ width: "100%", height: "100%", overflowY: "auto", padding: "0 28px", boxSizing: "border-box", background: "var(--surface-base)" }}>
      <div style={{ padding: "20px 0 4px", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 9 }}>
          <img src="../../assets/google-g.svg" alt="Google Wallet" title="Google Wallet" style={{ height: 18 }} />
          <span style={{ fontSize: 17, fontWeight: 600, color: "var(--typography-primary)" }}>Edit pass</span>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <div style={{ display: "flex", gap: 4 }}>
            <button onClick={onUndo} disabled={!canUndo} title="Undo" style={{ border: "none", background: "none", cursor: canUndo ? "pointer" : "default", opacity: canUndo ? 1 : 0.3, padding: "4px 6px", borderRadius: 7, color: "var(--typography-secondary)" }}>
              <svg width="16" height="16" viewBox="0 0 16 16" fill="none"><path d="M2 6h7a4 4 0 0 1 0 8H5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/><path d="M2 6l3-3M2 6l3 3" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>
            </button>
            <button onClick={onRedo} disabled={!canRedo} title="Redo" style={{ border: "none", background: "none", cursor: canRedo ? "pointer" : "default", opacity: canRedo ? 1 : 0.3, padding: "4px 6px", borderRadius: 7, color: "var(--typography-secondary)" }}>
              <svg width="16" height="16" viewBox="0 0 16 16" fill="none"><path d="M14 6H7a4 4 0 0 0 0 8h4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/><path d="M14 6l-3-3M14 6l-3 3" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>
            </button>
          </div>
          <div style={{ width: 1, height: 18, background: "var(--border-primary)" }} />
          <GPlatformToggle onApple={onApple} />
        </div>
      </div>

      <div style={{ padding: "8px 0 4px" }}>
        <button
          type="button"
          onClick={() => setGenerating(true)}
          style={{
            width: "100%", display: "flex", alignItems: "center", justifyContent: "center", gap: 7,
            padding: "9px 14px", borderRadius: 10, border: `1.5px solid ${accent}`,
            background: "transparent", cursor: "pointer", fontFamily: "var(--font-sans)",
            fontSize: 13, fontWeight: 600, color: accent, transition: "background .15s ease",
          }}
          onMouseEnter={(e) => { e.currentTarget.style.background = accent + "18"; }}
          onMouseLeave={(e) => { e.currentTarget.style.background = "transparent"; }}
        >
          <svg width="15" height="15" viewBox="0 0 15 15" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M7.5 1v13M1 7.5h13M3.5 3.5l8 8M11.5 3.5l-8 8" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
          </svg>
          Generate design
        </button>
      </div>

      <Section title="Colors">
        <RoleColorPicker pass={pass} set={set} accent={accent} />
      </Section>

      <Section title="Identity">
        <GLogoUpload src={pass.logoSrc} onUpload={(d) => set({ logoSrc: d })} onClear={() => set({ logoSrc: null })} />
        <div style={{ height: 6 }} />
        <FieldLabel>Icon · required by Apple Wallet</FieldLabel>
        <IconUpload src={pass.iconSrc} onUpload={(d) => set({ iconSrc: d })} onClear={() => set({ iconSrc: null })} />
        <div style={{ height: 6 }} />
        <FieldLabel>Issuer name (company)</FieldLabel>
        <GBF.Input value={pass.programName || ""} onChange={(e) => set({ programName: e.target.value })} placeholder="Breakfast Bonanza" />
        <div style={{ height: 6 }} />
        <FieldLabel>Card title (program name)</FieldLabel>
        <GBF.Input value={pass.cardTitle || ""} onChange={(e) => set({ cardTitle: e.target.value })} placeholder="Breakfast Bonanza Rewards" />
      </Section>

      <Section title="Module fields" hint="Fixed in v1">
        {[0, 1, 2].map((i) => (
          <TwoCol key={i}>
            <GBF.Input value={pass.fields?.[i]?.label || ""} disabled readOnly title="Fixed in v1" />
            <GBF.Input value={pass.fields?.[i]?.value || ""} disabled readOnly title="Fixed in v1" />
          </TwoCol>
        ))}
      </Section>

      <Section title="Hero image" hint="1032 × 336">
        <ImageUpload
          src={pass.heroSrc}
          hint="Hero / banner — 1032 × 336 px"
          previewH={56}
          cropTo={{ w: 1032, h: 336 }}
          onUpload={(d) => set({ heroSrc: d })}
          onClear={() => set({ heroSrc: null })}
        />
      </Section>

      <Section title="Barcode" hint={pass.barcode ? "On" : "Off"}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
          <FieldLabel>Show barcode</FieldLabel>
          <GBF.Switch checked={!!pass.barcode} onChange={(on) => set({ barcode: on ? { format: "qr", message: "SPN-4821-0093", altText: "4821 0093 5567" } : null })} />
        </div>
        {pass.barcode && (
          <Segmented
            options={[{ value: "qr", label: "QR" }, { value: "aztec", label: "Aztec" }, { value: "pdf417", label: "PDF417" }, { value: "code128", label: "Code128" }]}
            value={pass.barcode.format}
            onChange={(v) => set({ barcode: { ...pass.barcode, format: v } })}
          />
        )}
      </Section>

      <StoreLocations pass={pass} set={set} accent={accent} />

      <div style={{ display: "flex", gap: 10, padding: "20px 0 12px" }}>
        <GBF.Button style={{ flex: 1, background: accent, color: "#fff" }} onClick={() => setPublishing(true)}>Create my pass</GBF.Button>
        <GBF.Button variant="tertiary" onClick={handleSaveDraft} disabled={draftStatus === "saving"}>
          {draftStatus === "saving" ? "Saving…" : draftStatus === "saved" ? "Saved ✓" : draftStatus === "error" ? "Error" : "Save draft"}
        </GBF.Button>
      </div>
      {shareUrl && draftStatus === "saved" && (
        <div style={{ marginBottom: 20, padding: "10px 12px", borderRadius: 10, background: "var(--surface-secondary)", fontSize: 12, display: "flex", alignItems: "center", gap: 8 }}>
          <span style={{ flex: 1, color: "var(--typography-secondary)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{shareUrl}</span>
          <button onClick={() => navigator.clipboard.writeText(shareUrl)} style={{ border: "none", background: accent, color: "#fff", borderRadius: 7, padding: "4px 10px", cursor: "pointer", fontSize: 11, fontWeight: 600, whiteSpace: "nowrap" }}>Copy link</button>
        </div>
      )}

      {publishing && <PublishModal pass={pass} accent={accent} onClose={() => setPublishing(false)} />}
      {generating && (
        <GenerateDesignModal
          accent={accent}
          onApply={(patch) => {
            // Google uses heroSrc for banner, programName/cardTitle for brand names
            if (patch.stripSrc) { patch.heroSrc = patch.stripSrc; delete patch.stripSrc; }
            if (patch.company)  { patch.programName = patch.company; delete patch.company; }
            if (patch.name)     { patch.cardTitle = patch.name; delete patch.name; }
            set(patch);
            setGenerating(false);
          }}
          onClose={() => setGenerating(false)}
        />
      )}
    </div>
  );
}
window.GoogleBuilderForm = GoogleBuilderForm;
