
// Right-side lead detail drawer with 8-step pipeline and dynamic activity
const { useState: useStDr, useEffect: useEffDr } = React;

function LeadDrawer({ lead, agents, stages, onClose, onUpdate }) {
  const [agentOpen, setAgentOpen] = useStDr(false);
  const [callingState, setCallingState] = useStDr('idle'); // idle, loading, success, error
  const [callError, setCallError] = useStDr('');

  useEffDr(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);

  const handleTriggerCall = async () => {
    setCallingState('loading');
    setCallError('');
    
    try {
      const response = await fetch('https://api.nugget.com/unified-support/api/v1/ticketing/external/voice/getOrCreateIssue', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
          'Authorization': 'Basic ZGVtb251Z2dldEBudWdnZXQuY29tOmQ0NG8yN2IyODg2czczYzZvcGJnLWQ2bnQ0bGNqaW5yYzczOTBjMHBn'
        },
        body: JSON.stringify({
          businessPhoneNumber: '918035341451',
          userPhoneNumber: '919910988218',
          callDirection: 'outbound',
          journeyId: 'loan-followup-v1',
          journeyVersion: '1.0'
        })
      });

      if (response.ok) {
        const data = await response.json();
        console.log('✅ Call triggered successfully:', data);
        setCallingState('success');
        setTimeout(() => {
          setCallingState('idle');
        }, 3000);
      } else {
        const errorData = await response.json().catch(() => ({}));
        throw new Error(errorData.message || 'Failed to trigger call');
      }
    } catch (err) {
      console.error('❌ Error triggering call:', err);
      setCallError(err.message || 'Failed to trigger call. Please try again.');
      setCallingState('error');
      setTimeout(() => {
        setCallingState('idle');
      }, 3000);
    }
  };

  if (!lead) return null;

  const initials = lead.borrower.split(" ").map(w => w[0]).slice(0, 2).join("");
  const borrowerColor = ["#5684CC", "#A78BC7", "#4FA8A5", "#6BAE5B", "#D49A3A"][lead.id % 5];
  const agent = agents[lead.agentId];
  
  // Get pipeline step from lead data
  const pipelineStep = lead.pipelineStep || 0;
  const pipelineStages = window.LMS_DATA.pipelineStages || [];
  
  // Current stage label for badge
  const currentStageLabel = pipelineStages[pipelineStep]?.label || "Lead Created";
  
  // Action status based on pipeline step
  let actionStatus = "On track";
  let actionColor = "#3F7A33";
  if (pipelineStep === 7) {
    actionStatus = "Meeting confirmed";
    actionColor = "#3F7A33";
  } else if (lead.awaiting) {
    actionStatus = "Action pending";
    actionColor = "#8A6519";
  }

  return (
    <React.Fragment>
      <div onClick={onClose} className="drawerBackdrop" />
      <aside className="drawer" onClick={(e) => e.stopPropagation()}>
        {/* Sticky header */}
        <div style={{
          padding: "20px 24px 16px",
          borderBottom: "1px solid #ECECEA",
          background: "#fff",
          position: "sticky", top: 0, zIndex: 2,
        }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 14 }}>
            <span style={{ fontSize: 10.5, color: "#9CA3AF", letterSpacing: 0.5, textTransform: "uppercase" }}>
              Lead · NSF-{String(lead.id).padStart(4, "0")}
            </span>
            <button onClick={onClose} style={iconBtn} aria-label="Close"><Icons.x size={14} /></button>
          </div>
          <div style={{ display: "flex", gap: 14, alignItems: "center" }}>
            <Avatar initials={initials} color={borrowerColor} size={48} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 17, fontWeight: 500, color: "#1F2433", letterSpacing: -0.3 }}>
                {lead.borrower}
              </div>
              <div style={{ fontSize: 12.5, color: "#6B7280", marginTop: 2 }}>
                {lead.business}
                <span style={{ margin: "0 7px", color: "#D4D4D2" }}>•</span>
                {lead.city}
              </div>
            </div>
          </div>

          <div style={{ display: "flex", gap: 6, marginTop: 14 }}>
            <a href={`tel:${lead.phone.replace(/\s/g, "")}`} onClick={(e) => e.preventDefault()} style={chipLink}>
              <Icons.phone size={12} />
              {lead.phone}
            </a>
            <a href={`mailto:${lead.email}`} onClick={(e) => e.preventDefault()} style={chipLink}>
              <Icons.mail size={12} />
              {lead.email}
            </a>
          </div>
        </div>

        {/* Body */}
        <div style={{ padding: "20px 24px", display: "flex", flexDirection: "column", gap: 22 }}>

          {/* Loan summary */}
          <section>
            <SectionHeader label="Loan details" />
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14, marginTop: 10 }}>
              <Field label="Loan ask">
                <span style={{ fontSize: 22, fontWeight: 600, color: "#1F2433", letterSpacing: -0.4 }}>
                  {formatINR(lead.amount)}
                </span>
                <div style={{ fontSize: 11, color: "#9CA3AF", marginTop: 2, fontVariantNumeric: "tabular-nums" }}>
                  {formatINRFull(lead.amount)}
                </div>
              </Field>
              <Field label="Stage">
                <div style={{ marginTop: 2 }}>
                  <span style={{
                    display: "inline-flex", alignItems: "center", gap: 6,
                    padding: "4px 10px",
                    borderRadius: 999,
                    background: "#FBF4E6",
                    color: "#8A6519",
                    fontSize: 12,
                    fontWeight: 500,
                    lineHeight: 1.2,
                    whiteSpace: "nowrap",
                    border: "1px solid #8A65191f",
                  }}>
                    <span style={{ width: 6, height: 6, borderRadius: 999, background: "#D49A3A" }} />
                    {currentStageLabel}
                  </span>
                </div>
              </Field>
              <Field label="Business Type">
                <span style={{ fontSize: 13, color: "#1F2433" }}>{lead.sector}</span>
              </Field>
              <Field label="Years in Business">
                <span style={{ fontSize: 13, color: "#1F2433" }}>{lead.vintage}</span>
              </Field>
              <Field label="Action status">
                {lead.awaiting && pipelineStep < 7 ? (
                  <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 12.5, color: "#8A6519", fontWeight: 500 }}>
                    <span className="pulseDot" style={{ width: 7, height: 7, borderRadius: 999, background: "#D49A3A" }} />
                    Action pending
                  </span>
                ) : (
                  <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 12.5, color: actionColor, fontWeight: 500 }}>
                    <Icons.check size={13} /> {actionStatus}
                  </span>
                )}
              </Field>
            </div>
          </section>

          {/* 8-step Pipeline Progress */}
          <section>
            <SectionHeader label="Pipeline progress" />
            <div style={{ marginTop: 14, position: "relative", overflowX: "auto", paddingBottom: 8 }}>
              <div style={{ display: "flex", justifyContent: "space-between", minWidth: 800, gap: 4 }}>
                {pipelineStages.map((stage, i) => {
                  const isDone = i < pipelineStep;
                  const isCurrent = i === pipelineStep;
                  const isFuture = i > pipelineStep;
                  return (
                    <div key={i} style={{ 
                      display: "flex", 
                      flexDirection: "column", 
                      alignItems: "center", 
                      flex: 1, 
                      minWidth: 85,
                      gap: 8,
                      position: "relative"
                    }}>
                      {/* Connector line */}
                      {i < pipelineStages.length - 1 && (
                        <div style={{
                          position: "absolute",
                          top: 7,
                          left: "50%",
                          right: "-50%",
                          height: 2,
                          background: isDone ? "#D49A3A" : "#ECECEA",
                          zIndex: 0,
                        }} />
                      )}
                      
                      {/* Step indicator */}
                      <span style={{
                        width: 14, height: 14, borderRadius: 999,
                        background: (isDone || isCurrent) ? "#D49A3A" : "#fff",
                        border: "2px solid " + ((isDone || isCurrent) ? "#D49A3A" : "#ECECEA"),
                        transition: "all 200ms ease",
                        zIndex: 1,
                        position: "relative",
                      }} />
                      
                      {/* Label */}
                      <span style={{
                        fontSize: 9.5,
                        color: isCurrent ? "#1F2433" : (isDone ? "#6B7280" : "#9CA3AF"),
                        fontWeight: isCurrent ? 600 : 400,
                        textAlign: "center",
                        lineHeight: 1.3,
                        maxWidth: 80,
                      }}>{stage.label}</span>
                      
                      {/* Date */}
                      <span style={{ 
                        fontSize: 9.5, 
                        color: (isDone || isCurrent) ? "#6B7280" : "#D4D4D2",
                        fontVariantNumeric: "tabular-nums"
                      }}>{stage.date}</span>
                    </div>
                  );
                })}
              </div>
            </div>
          </section>

          {/* Activity Timeline */}
          <section>
            <SectionHeader label="Activity Timeline" />
            <div style={{ marginTop: 16, display: "flex", flexDirection: "column", gap: 0, background: "#FCFCFB", borderRadius: 10, padding: "16px 14px", border: "1px solid #ECECEA" }}>
              {[
                { title: 'Lead Created', desc: 'Lead captured via FOS visit and routed to campaign queue.' },
                { title: 'Application Link Sent', desc: 'Application form sent to borrower via WhatsApp.' },
                { title: 'Intelligence Trigger', desc: 'Form inactive for 2 hours. Nugget escalated to voice channel.', tone: 'amber' },
                { title: 'Call Triggered — User Busy', desc: 'Outbound call initiated. Borrower unavailable. Retry scheduled.' },
                { title: 'Call Connected', desc: 'Call connected. Business details captured and documents uploaded by borrower.' },
                { title: 'Form Completed', desc: 'All fields auto-populated from call and documents. Application submitted.' },
                { title: 'Sent to Credit Team', desc: 'Complete profile forwarded for credit assessment.' },
                { title: 'Credit Plan Generated', desc: 'Assessment complete. ₹40L at 17% p.a. · 36 months · Processing fee 2%.' },
                { title: 'Offer Call — Terms Negotiated', desc: 'Loan plan presented. Rate objection handled. Processing fee waived. Tenure extended to 54 months.' },
                { title: 'Meeting Scheduled with FOS Agent', desc: 'In-person meeting confirmed with Vikram K.' },
                { title: 'Meeting with FOS Agent — Offer Closed', desc: 'In-person meeting held with Vikram K. Final terms discussed and loan offer accepted.', tone: 'success' },
              ].map((step, i) => (
                <div key={i} style={{
                  display: "flex",
                  gap: 14,
                  paddingBottom: i === 10 ? 0 : 18,
                  position: "relative",
                }}>
                  {/* Vertical line connector */}
                  {i < 10 && (
                    <div style={{
                      position: "absolute",
                      left: 9.5,
                      top: 26,
                      bottom: 0,
                      width: 2.5,
                      background: step.tone === 'amber' ? "linear-gradient(to bottom, #F59E0B 0%, #E5E7EB 100%)" : (i === 9 ? "linear-gradient(to bottom, #3B82F6 0%, #10B981 100%)" : "#E5E7EB"),
                      borderRadius: 2,
                    }} />
                  )}
                  
                  {/* Step indicator */}
                  <div style={{
                    width: 20,
                    height: 20,
                    borderRadius: "50%",
                    background: step.tone === 'success' ? "#10B981" : step.tone === 'amber' ? "#F59E0B" : "#5684CC",
                    flexShrink: 0,
                    marginTop: 1,
                    zIndex: 1,
                    boxShadow: step.tone === 'success' ? "0 2px 8px rgba(16, 185, 129, 0.35)" : step.tone === 'amber' ? "0 2px 8px rgba(245, 158, 11, 0.4)" : "0 1px 3px rgba(86, 132, 204, 0.25)",
                    border: step.tone === 'success' ? "2px solid #fff" : step.tone === 'amber' ? "2px solid #fff" : "2px solid #fff",
                  }} />
                  
                  {/* Content */}
                  <div style={{
                    flex: 1,
                    background: step.tone === 'amber' ? "linear-gradient(135deg, #FEF3C7 0%, #FDE68A 100%)" : step.tone === 'success' ? "linear-gradient(135deg, #D1FAE5 0%, #A7F3D0 100%)" : "transparent",
                    padding: step.tone === 'amber' || step.tone === 'success' ? "10px 14px" : "1px 0",
                    borderRadius: step.tone === 'amber' || step.tone === 'success' ? 10 : 0,
                    border: step.tone === 'amber' ? "1.5px solid #FBBF24" : step.tone === 'success' ? "1.5px solid #34D399" : "none",
                    boxShadow: step.tone === 'amber' ? "0 2px 6px rgba(251, 191, 36, 0.15)" : step.tone === 'success' ? "0 2px 6px rgba(52, 211, 153, 0.15)" : "none",
                  }}>
                    <div style={{
                      fontSize: 13,
                      fontWeight: 600,
                      color: step.tone === 'success' ? "#065F46" : step.tone === 'amber' ? "#78350F" : "#1F2433",
                      marginBottom: 3,
                      letterSpacing: "-0.01em",
                    }}>{step.title}</div>
                    <div style={{
                      fontSize: 12,
                      color: step.tone === 'success' ? "#047857" : step.tone === 'amber' ? "#92400E" : "#6B7280",
                      lineHeight: 1.5,
                      fontWeight: step.tone === 'amber' || step.tone === 'success' ? 500 : 400,
                    }}>{step.desc}</div>
                  </div>
                </div>
              ))}
            </div>
          </section>
        </div>

        {/* Sticky footer */}
        <div style={{
          position: "sticky", bottom: 0,
          padding: "14px 24px",
          background: "#fff",
          borderTop: "1px solid #ECECEA",
          display: "flex", gap: 8,
        }}>
          <button
            onClick={handleTriggerCall}
            disabled={callingState === 'loading'}
            style={{
              ...btnCallDrawer,
              flex: 1,
              opacity: callingState === 'loading' ? 0.7 : 1,
              cursor: callingState === 'loading' ? 'not-allowed' : 'pointer'
            }}
          >
            {callingState === 'loading' ? (
              <>
                <span style={{
                  display: 'inline-block',
                  width: 14,
                  height: 14,
                  border: '2px solid #fff',
                  borderTopColor: 'transparent',
                  borderRadius: '50%',
                  animation: 'spin 0.6s linear infinite'
                }} />
                Calling...
              </>
            ) : callingState === 'success' ? (
              <>
                <Icons.check size={13} />
                Call Triggered
              </>
            ) : callingState === 'error' ? (
              <>
                <Icons.x size={13} />
                Call Failed
              </>
            ) : (
              <>
                <Icons.phone size={13} />
                Trigger Call
              </>
            )}
          </button>
          <a href="timeline.html" target="_blank" style={{ ...btnDarkDrawer, flex: 1, textDecoration: "none" }}>
            View full application <Icons.arrow size={13} />
          </a>
        </div>
      </aside>
    </React.Fragment>
  );
}

function SectionHeader({ label, action }) {
  return (
    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
      <span style={{ fontSize: 10.5, color: "#9CA3AF", letterSpacing: 0.6, textTransform: "uppercase", fontWeight: 500 }}>{label}</span>
      {action}
    </div>
  );
}

function Field({ label, children }) {
  return (
    <div style={{ minWidth: 0 }}>
      <div style={{ fontSize: 10.5, color: "#9CA3AF", letterSpacing: 0.4, textTransform: "uppercase", marginBottom: 4 }}>{label}</div>
      <div style={{ minWidth: 0 }}>{children}</div>
    </div>
  );
}

const iconBtn = {
  width: 28, height: 28, borderRadius: 6,
  display: "inline-flex", alignItems: "center", justifyContent: "center",
  background: "#fff", border: "1px solid #ECECEA",
  cursor: "pointer", color: "#6B7280",
};
const chipLink = {
  display: "inline-flex", alignItems: "center", gap: 6,
  padding: "5px 10px", borderRadius: 6,
  background: "#FCFCFB", border: "1px solid #ECECEA",
  fontSize: 11.5, color: "#1F2433",
  textDecoration: "none", cursor: "pointer",
};
const btnDarkDrawer = {
  height: 38, border: "none", background: "#1F2433", color: "#fff",
  borderRadius: 8, fontSize: 12.5, fontWeight: 500,
  display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 6,
  cursor: "pointer", fontFamily: "inherit",
};
const btnCallDrawer = {
  height: 38, border: "1px solid #4CAF50", background: "#fff", color: "#4CAF50",
  borderRadius: 8, fontSize: 12.5, fontWeight: 500,
  display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 6,
  cursor: "pointer", fontFamily: "inherit",
  transition: "all 0.2s ease",
};

Object.assign(window, { LeadDrawer });
