frappe.ui.form.on("Tax Period Closing Wizard", {
	onload(frm) {
		// Expand form to full width
		frm.$wrapper.find(".form-column, .section-body, .form-section").css("max-width", "100%");
		$(`<style>
			[data-doctype="Tax Period Closing Wizard"] .form-section .section-body {
				max-width: 100% !important;
			}
			[data-doctype="Tax Period Closing Wizard"] .form-column {
				max-width: 100% !important;
			}
			[data-doctype="Tax Period Closing Wizard"] .row.form-section {
				max-width: 100% !important;
			}
			[data-doctype="Tax Period Closing Wizard"] .frappe-control[data-fieldtype="Table"] {
				max-width: 100% !important;
			}
			[data-doctype="Tax Period Closing Wizard"] .form-layout {
				max-width: 100% !important;
			}
			[data-doctype="Tax Period Closing Wizard"] .layout-main .layout-main-section {
				max-width: 100% !important;
			}
			[data-doctype="Tax Period Closing Wizard"] .form-page {
				max-width: 100% !important;
			}
		</style>`).appendTo("head");
	},

	refresh(frm) {
		frm.trigger("render_progress_bar");
		frm.trigger("render_benefits_html");
		frm.trigger("render_log_html");
		frm.trigger("render_summary_html");
		frm.trigger("setup_buttons");
		frm.trigger("color_tax_items");
		frm.trigger("bind_realtime");
	},

	setup_buttons(frm) {
		if (frm.doc.docstatus === 1 || frm.doc.docstatus === 2) return;

		if (frm.doc.wizard_status === "Draft" || frm.doc.wizard_status === "Error") {
			frm.add_custom_button(__("Calculate Taxes"), () => {
				frm.trigger("run_calculate");
			}, __("Actions")).addClass("btn-primary");
		}

		if (frm.doc.wizard_status === "Calculated") {
			frm.add_custom_button(__("Create Journal Entries"), () => {
				frappe.confirm(
					__("This will create journal entries for all calculated taxes. Continue?"),
					() => frm.trigger("run_create_entries")
				);
			}, __("Actions")).addClass("btn-primary");

			frm.add_custom_button(__("Re-calculate"), () => {
				frm.trigger("run_calculate");
			}, __("Actions"));
		}

		// Verify & Fix buttons — available after calculation
		if (frm.doc.wizard_status !== "Draft") {
			frm.add_custom_button(__("Verify Entries (Kassa)"), () => {
				frm.trigger("run_verify");
			}, __("Actions"));

			frm.add_custom_button(__("Fix Cash Method Entries"), () => {
				frappe.confirm(
					__("This will create correction Journal Entries to move VAT from 521.3 to 245.1 and revenue from 601 to 542 for all unpaid Sales Invoices. Continue?"),
					() => frm.trigger("run_fix_cash")
				);
			}, __("Actions"));
		}

		if (frm.doc.wizard_status === "Entries Created") {
			frm.add_custom_button(__("Rollback All Entries"), () => {
				frappe.confirm(
					__("This will cancel/delete ALL journal entries created by this wizard. Are you sure?"),
					() => frm.trigger("run_rollback")
				);
			}, __("Actions")).addClass("btn-danger");
		}
	},

	// ── Realtime binding ──────────────────────────────────

	bind_realtime(frm) {
		// Avoid duplicate bindings
		if (frm._tpcw_realtime_bound) return;
		frm._tpcw_realtime_bound = true;

		frappe.realtime.on("tpcw_progress", (data) => {
			if (data.name !== frm.doc.name) return;
			frm.trigger("update_live_progress", data);
		});
	},

	update_live_progress(frm, data) {
		if (!data) return;

		const pct = data.percent || 0;
		const phase = data.phase || "";
		const message = data.message || "";
		const level = data.level || "Info";

		// Update the progress bar
		const $wrapper = frm.fields_dict.progress_bar_html.$wrapper;

		const level_colors = {
			"Info": { bar: "linear-gradient(90deg, #007bff, #6610f2)", text: "#007bff", pulse: "#007bff" },
			"Success": { bar: "linear-gradient(90deg, #28a745, #20c997)", text: "#28a745", pulse: "#28a745" },
			"Warning": { bar: "linear-gradient(90deg, #fd7e14, #ffc107)", text: "#e67e22", pulse: "#fd7e14" },
			"Error": { bar: "linear-gradient(90deg, #dc3545, #c82333)", text: "#dc3545", pulse: "#dc3545" },
		};
		const colors = level_colors[level] || level_colors["Info"];

		const is_complete = pct >= 100 || phase === "Complete";
		const pulse_css = is_complete ? "" : "animation: tpcw-pulse 1.5s ease-in-out infinite;";

		$wrapper.html(`
			<style>
				@keyframes tpcw-pulse {
					0%, 100% { opacity: 1; }
					50% { opacity: 0.6; }
				}
				@keyframes tpcw-bar-stripe {
					0% { background-position: 1rem 0; }
					100% { background-position: 0 0; }
				}
			</style>
			<div style="margin-bottom: 15px;">
				<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 6px;">
					<div>
						<span style="font-weight: bold; color: ${colors.text}; font-size: 13px; ${pulse_css}">
							${is_complete ? "✓" : "⟳"} ${phase}
						</span>
						<span style="color: #666; font-size: 12px; margin-left: 8px;">
							${frappe.utils.escape_html(message)}
						</span>
					</div>
					<span style="font-weight: bold; font-size: 14px; color: ${colors.text};">${pct}%</span>
				</div>
				<div style="background: #e9ecef; border-radius: 8px; overflow: hidden; height: 26px; position: relative;">
					<div style="
						width: ${pct}%;
						height: 100%;
						background: ${colors.bar};
						${!is_complete ? `background-image: linear-gradient(45deg, rgba(255,255,255,.15) 25%, transparent 25%, transparent 50%, rgba(255,255,255,.15) 50%, rgba(255,255,255,.15) 75%, transparent 75%, transparent);
						background-size: 1rem 1rem;
						animation: tpcw-bar-stripe 0.8s linear infinite;` : ""}
						border-radius: 8px;
						transition: width 0.4s ease;
						display: flex;
						align-items: center;
						justify-content: center;
						color: white;
						font-weight: bold;
						font-size: 12px;
						text-shadow: 0 1px 2px rgba(0,0,0,0.3);
					">${pct > 8 ? pct + "%" : ""}</div>
				</div>
			</div>
		`);

		// If complete, show a success banner
		if (is_complete && level === "Success") {
			frappe.show_alert({
				message: message,
				indicator: "green"
			}, 7);
		}
	},

	// ── Run actions ───────────────────────────────────────

	run_calculate(frm) {
		frm.save().then(() => {
			frm.trigger("update_live_progress", {
				percent: 2,
				phase: "Starting",
				message: "Initializing wizard...",
				level: "Info"
			});

			frappe.call({
				method: "taxes_az.taxes_az.doctype.tax_period_closing_wizard.tax_period_closing_wizard.run_wizard",
				args: { name: frm.doc.name },
				freeze: true,
				freeze_message: __("Calculating taxes..."),
				callback(r) {
					if (r && r.message) {
						frappe.show_alert({
							message: __("Calculation complete. Reloading..."),
							indicator: "green"
						});
					}
					// Force full page reload to get all child table data
					window.location.reload();
				},
				error(r) {
					frappe.show_alert({
						message: __("Calculation failed. Check browser console."),
						indicator: "red"
					});
					window.location.reload();
				}
			});
		});
	},

	run_create_entries(frm) {
		frm.trigger("update_live_progress", {
			percent: 81,
			phase: "Entry Creation",
			message: "Preparing journal entries...",
			level: "Info"
		});

		frappe.call({
			method: "taxes_az.taxes_az.doctype.tax_period_closing_wizard.tax_period_closing_wizard.create_entries",
			args: { name: frm.doc.name },
			freeze: true,
			freeze_message: __("Creating journal entries..."),
			callback(r) {
				if (r && r.message) {
					frappe.show_alert({
						message: __("Entries created. Reloading..."),
						indicator: "green"
					});
				}
				window.location.reload();
			},
			error() {
				frappe.show_alert({
					message: __("Entry creation failed."),
					indicator: "red"
				});
				window.location.reload();
			}
		});
	},

	run_fix_cash(frm) {
		frappe.call({
			method: "taxes_az.taxes_az.doctype.tax_period_closing_wizard.tax_period_closing_wizard.fix_cash_method_entries",
			args: { name: frm.doc.name },
			freeze: true,
			freeze_message: __("Re-submitting invoices with cash method accounts..."),
			callback(r) {
				if (!r || !r.message) return;
				const data = r.message;

				if (data.status === "skip" || data.status === "error") {
					frappe.msgprint({ message: data.message, indicator: "red" });
					return;
				}

				const s = data.summary || {};
				const fmt = (v) => parseFloat(v || 0).toLocaleString("az-AZ", {minimumFractionDigits: 2});

				let html = `<div style="font-family: -apple-system, sans-serif;">`;

				html += `<div style="padding: 12px; background: #2c3e50; color: white; border-radius: 6px; margin-bottom: 12px;">
					<strong>${__("Cash method — invoices re-submitted")}</strong>
				</div>`;

				html += `<table class="table table-bordered" style="font-size: 13px;">
					<tr style="background: #d4edda;">
						<td><strong>${__("Fixed invoices")}</strong></td>
						<td>${s.invoices_fixed}</td>
						<td>ƏDV: ${fmt(s.total_vat_moved)} AZN → 245.1</td>
						<td>Gəlir: ${fmt(s.total_revenue_deferred)} AZN → 542</td>
					</tr>
					<tr><td>${__("Skipped")}</td><td colspan="3">${s.skipped}</td></tr>
					<tr style="${s.errors > 0 ? 'background:#f8d7da;' : ''}">
						<td>${__("Errors")}</td><td colspan="3">${s.errors}</td></tr>
				</table>`;

				if ((data.fixed || []).length > 0) {
					html += `<table class="table table-sm table-bordered" style="font-size: 12px;">
						<thead style="background: #343a40; color: white;">
							<tr><th>${__("Invoice")}</th><th style="text-align:right;">ƏDV → 245.1</th><th style="text-align:right;">Gəlir → 542</th><th>${__("Changes")}</th></tr>
						</thead><tbody>`;
					for (const f of data.fixed) {
						html += `<tr>
							<td><a href="/app/sales-invoice/${f.invoice}">${f.invoice}</a></td>
							<td style="text-align:right;">${fmt(f.vat)}</td>
							<td style="text-align:right;">${fmt(f.revenue)}</td>
							<td style="font-size:11px;color:#666;">${(f.changes || []).join("<br>")}</td>
						</tr>`;
					}
					html += `</tbody></table>`;
				}

				if ((data.errors || []).length > 0) {
					for (const e of data.errors) {
						html += `<div style="padding:6px;background:#f8d7da;border-radius:3px;margin-bottom:4px;">
							✗ ${e.invoice}: ${frappe.utils.escape_html(e.error)}</div>`;
					}
				}

				html += `</div>`;
				frappe.msgprint({
					title: __("Cash Method — Fix Result"),
					message: html,
					indicator: (s.errors || 0) > 0 ? "orange" : "green",
					wide: true,
				});
			}
		});
	},

	run_verify(frm) {
		frappe.call({
			method: "taxes_az.taxes_az.doctype.tax_period_closing_wizard.tax_period_closing_wizard.verify_entries",
			args: { name: frm.doc.name },
			freeze: true,
			freeze_message: __("Verifying entries..."),
			callback(r) {
				if (!r || !r.message) return;
				const data = r.message;
				const s = data.summary || {};

				let html = `<div style="font-family: -apple-system, sans-serif; max-height: 500px; overflow-y: auto;">`;

				// Header
				html += `<div style="padding: 10px; background: #2c3e50; color: white; border-radius: 6px 6px 0 0; margin-bottom: 0;">
					<strong>${__("Accounting method:")} ${data.method}</strong> |
					${__("Invoices:")} ${s.total_invoices || 0} |
					<span style="color: #2ecc71;">${__("Correct:")} ${s.correct || 0}</span> |
					<span style="color: #e74c3c;">${__("Error:")} ${s.errors || 0}</span> |
					<span style="color: #f39c12;">${__("Warning:")} ${s.warnings || 0}</span>
				</div>`;

				// Issues
				if ((data.issues || []).length > 0) {
					html += `<div style="border: 1px solid #e74c3c; border-top: none; border-radius: 0 0 6px 6px; padding: 10px;">`;
					for (const issue of data.issues) {
						const color = issue.type === "error" ? "#e74c3c" : "#f39c12";
						const icon = issue.type === "error" ? "✗" : "⚠";
						html += `<div style="padding: 8px; margin-bottom: 6px; border-left: 4px solid ${color}; background: ${issue.type === 'error' ? '#fdf0ef' : '#fffbeb'}; border-radius: 3px;">
							<span style="color: ${color}; font-weight: bold;">${icon}</span>
							<a href="/app/sales-invoice/${issue.invoice}"><strong>${issue.invoice}</strong></a>:
							${frappe.utils.escape_html(issue.message)}
							<div style="margin-top: 4px; font-size: 11px; color: #666;">
								${__("Fix:")} ${frappe.utils.escape_html(issue.fix || "")}
							</div>
						</div>`;
					}
					if (s.total_wrong_vat > 0) {
						html += `<div style="padding: 10px; background: #f8d7da; border-radius: 4px; font-weight: bold; color: #721c24;">
							${__("Total incorrect VAT:")} ${parseFloat(s.total_wrong_vat).toLocaleString("az-AZ", {minimumFractionDigits: 2})} AZN
						</div>`;
					}
					html += `</div>`;
				}

				// OK entries
				if ((data.ok || []).length > 0) {
					html += `<details style="margin-top: 10px;"><summary style="cursor: pointer; color: #27ae60; font-weight: bold;">
						✓ ${__("Correct entries")} (${data.ok.length})</summary>
						<div style="padding: 8px; font-size: 12px; color: #555;">`;
					for (const ok of data.ok) {
						html += `<div style="padding: 2px 0;">✓ ${frappe.utils.escape_html(ok)}</div>`;
					}
					html += `</div></details>`;
				}

				html += `</div>`;

				frappe.msgprint({
					title: __("Cash Method — Verification Result"),
					message: html,
					indicator: (s.errors || 0) > 0 ? "red" : ((s.warnings || 0) > 0 ? "orange" : "green"),
					wide: true,
				});
			}
		});
	},

	run_rollback(frm) {
		frappe.call({
			method: "taxes_az.taxes_az.doctype.tax_period_closing_wizard.tax_period_closing_wizard.rollback",
			args: { name: frm.doc.name },
			freeze: true,
			freeze_message: __("Rolling back entries..."),
			callback(r) {
				if (r.message) {
					frm.reload_doc();
					frappe.show_alert({
						message: __("All entries rolled back"),
						indicator: "orange"
					});
				}
			}
		});
	},

	company(frm) {
		if (frm.doc.company) {
			frappe.db.get_value("Company", frm.doc.company, [
				"cost_center", "tax_id", "default_currency"
			]).then(r => {
				if (r.message) {
					if (!frm.doc.cost_center) {
						frm.set_value("cost_center", r.message.cost_center);
					}
					frm.set_value("company_voen", r.message.tax_id || "");
				}
			});
		}
	},

	period_type(frm) {
		if (frm.doc.period_type === "Monthly") {
			frm.set_value("quarter", "");
		} else if (frm.doc.period_type === "Quarterly") {
			frm.set_value("month", "");
		} else {
			frm.set_value("quarter", "");
			frm.set_value("month", "");
		}
	},

	// ── Static Progress Bar (for saved state) ─────────────

	render_progress_bar(frm) {
		const pct = frm.doc.progress_percent || 0;
		const status = frm.doc.wizard_status || "Draft";

		const status_config = {
			"Draft": { color: "#6c757d", icon: "○", bar: "linear-gradient(90deg, #6c757d, #adb5bd)" },
			"Calculated": { color: "#fd7e14", icon: "◉", bar: "linear-gradient(90deg, #fd7e14, #ffc107)" },
			"Entries Created": { color: "#28a745", icon: "✓", bar: "linear-gradient(90deg, #28a745, #20c997)" },
			"Completed": { color: "#28a745", icon: "✓", bar: "linear-gradient(90deg, #28a745, #20c997)" },
			"Error": { color: "#dc3545", icon: "✗", bar: "linear-gradient(90deg, #dc3545, #c82333)" },
			"Cancelled": { color: "#6c757d", icon: "—", bar: "linear-gradient(90deg, #6c757d, #adb5bd)" }
		};

		const cfg = status_config[status] || status_config["Draft"];

		const html = `
			<div style="margin-bottom: 15px;">
				<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 6px;">
					<span style="font-weight: bold; color: ${cfg.color}; font-size: 13px;">
						${cfg.icon} ${status}
					</span>
					<span style="font-weight: bold; font-size: 14px; color: ${cfg.color};">${pct}%</span>
				</div>
				<div style="background: #e9ecef; border-radius: 8px; overflow: hidden; height: 26px;">
					<div style="
						width: ${pct}%;
						height: 100%;
						background: ${cfg.bar};
						border-radius: 8px;
						transition: width 0.5s ease;
						display: flex;
						align-items: center;
						justify-content: center;
						color: white;
						font-weight: bold;
						font-size: 12px;
						text-shadow: 0 1px 2px rgba(0,0,0,0.3);
					">${pct > 8 ? pct + "%" : ""}</div>
				</div>
			</div>
		`;
		frm.fields_dict.progress_bar_html.$wrapper.html(html);
	},

	// ── Benefits Display ──────────────────────────────────

	render_benefits_html(frm) {
		const benefits = frm.doc.detected_benefits || [];
		if (!benefits.length) {
			if (frm.fields_dict.benefits_html) {
				frm.fields_dict.benefits_html.$wrapper.html(
					frm.doc.wizard_status === "Draft"
						? `<div style="padding: 15px; text-align: center; color: #999;">${__("Benefits will be detected after calculation.")}</div>`
						: `<div style="padding: 15px; text-align: center; color: #999;">${__("No special tax benefits detected.")}</div>`
				);
			}
			return;
		}

		let html = '<div style="display: flex; flex-direction: column; gap: 10px;">';

		for (const b of benefits) {
			const is_on = b.enabled;
			const cond = b.condition_met || "No";

			// Colors
			let border_color, bg_color, icon, badge_bg, badge_text;
			if (cond === "Yes" && is_on) {
				border_color = "#28a745"; bg_color = "#f0fdf4"; icon = "✓"; badge_bg = "#28a745"; badge_text = __("Active");
			} else if (cond === "No") {
				border_color = "#dc3545"; bg_color = "#fef2f2"; icon = "✗"; badge_bg = "#dc3545"; badge_text = __("Not Met");
			} else if (cond === "Manual Check") {
				border_color = "#fd7e14"; bg_color = "#fffbeb"; icon = "?"; badge_bg = "#fd7e14"; badge_text = __("Manual Check");
			} else if (!is_on) {
				border_color = "#6c757d"; bg_color = "#f8f9fa"; icon = "—"; badge_bg = "#6c757d"; badge_text = __("Disabled");
			} else {
				border_color = "#17a2b8"; bg_color = "#f0f9ff"; icon = "~"; badge_bg = "#17a2b8"; badge_text = __("Partial");
			}

			const reduction_html = b.tax_reduction
				? `<div style="margin-top: 6px; font-size: 14px; font-weight: bold; color: #28a745;">
					${__("Tax Reduction:")} ${format_currency(b.tax_reduction)}
				   </div>`
				: "";

			const law_text = b.law_url
				? `<a href="${frappe.utils.escape_html(b.law_url)}" target="_blank" style="color:#4338ca;text-decoration:underline;">${frappe.utils.escape_html(b.law_reference)}</a>`
				: frappe.utils.escape_html(b.law_reference);
			const law_html = b.law_reference
				? `<div style="margin-top: 8px; padding: 8px 10px; background: #eef2ff; border-left: 3px solid #6366f1; border-radius: 3px; font-size: 11px; color: #4338ca; line-height: 1.5;">
					<span style="font-weight: bold;">${__("Law:")}</span> ${law_text}
				   </div>`
				: "";

			html += `
				<div style="border-left: 4px solid ${border_color}; background: ${bg_color}; border-radius: 6px; padding: 12px 16px;">
					<div style="display: flex; justify-content: space-between; align-items: flex-start;">
						<div style="flex: 1;">
							<div style="display: flex; align-items: center; gap: 8px; margin-bottom: 4px;">
								<span style="font-size: 16px; font-weight: bold; color: ${border_color};">${icon}</span>
								<span style="font-weight: bold; font-size: 13px; color: #333;">
									${frappe.utils.escape_html(b.article)}
								</span>
								<span style="background: ${badge_bg}; color: white; padding: 2px 8px; border-radius: 10px; font-size: 11px;">
									${badge_text}
								</span>
							</div>
							<div style="font-size: 13px; color: #444; margin-bottom: 4px;">
								<strong>${frappe.utils.escape_html(b.benefit_name)}</strong>
							</div>
							<div style="font-size: 12px; color: #666; margin-bottom: 2px;">
								${__("Applies to:")} <strong>${frappe.utils.escape_html(b.applies_to)}</strong>
								&nbsp;|&nbsp; ${__("Exemption:")} <strong>${b.exemption_percent}%</strong>
							</div>
							<div style="font-size: 12px; color: #555; margin-top: 6px; padding: 8px; background: rgba(0,0,0,0.03); border-radius: 4px;">
								${frappe.utils.escape_html(b.condition_details || "")}
							</div>
							${reduction_html}
							${law_html}
						</div>
					</div>
				</div>
			`;
		}

		html += "</div>";
		if (frm.fields_dict.benefits_html) {
			frm.fields_dict.benefits_html.$wrapper.html(html);
		}
	},

	// ── Log Display ────────────────────────────────────────

	render_log_html(frm) {
		const logs = frm.doc.log_entries || [];
		if (!logs.length) {
			frm.fields_dict.log_html.$wrapper.html(
	`<div style="padding: 20px; text-align: center; color: #999;">${__('No log entries yet. Click "Calculate Taxes" to begin.')}</div>`
			);
			return;
		}

		const level_styles = {
			"Header": "background: #2c3e50; color: #ecf0f1; font-weight: bold; padding: 6px 10px; margin-top: 8px;",
			"Info": "color: #2980b9; padding: 3px 10px;",
			"Success": "color: #27ae60; padding: 3px 10px;",
			"Warning": "color: #e67e22; padding: 3px 10px; font-weight: 500;",
			"Error": "color: #e74c3c; padding: 3px 10px; font-weight: bold; background: #fdf0ef;"
		};

		const level_icons = {
			"Header": "═══",
			"Info": "ℹ",
			"Success": "✓",
			"Warning": "⚠",
			"Error": "✗"
		};

		let html = '<div style="font-family: monospace; font-size: 12px; background: #fafbfc; border: 1px solid #e1e4e8; border-radius: 6px; max-height: 600px; overflow-y: auto; padding: 8px;">';

		for (const log of logs) {
			const style = level_styles[log.level] || level_styles["Info"];
			const icon = level_icons[log.level] || "·";
			const ts = log.timestamp ? frappe.datetime.str_to_user(log.timestamp).split(" ")[1] || "" : "";

			html += `<div style="${style} border-radius: 3px; margin-bottom: 1px;">`;
			if (log.level !== "Header") {
				html += `<span style="color: #999; margin-right: 8px;">[${ts}]</span>`;
			}
			html += `<span style="margin-right: 6px;">${icon}</span>`;
			html += `${frappe.utils.escape_html(log.message)}`;
			html += `</div>`;
		}

		html += "</div>";
		frm.fields_dict.log_html.$wrapper.html(html);
	},

	// ── Summary Display ───────────────────────────────────

	render_summary_html(frm) {
		if (frm.doc.wizard_status !== "Entries Created" && frm.doc.wizard_status !== "Completed") {
			frm.fields_dict.summary_html.$wrapper.html("");
			return;
		}

		const items = frm.doc.tax_items || [];
		const je_list = frm.doc.journal_entries || [];
		const payroll = frm.doc.payroll_summary || [];

		let html = '<div style="font-family: -apple-system, BlinkMacSystemFont, sans-serif;">';

		html += `
			<table class="table table-bordered" style="font-size: 13px;">
				<thead style="background: #2c3e50; color: white;">
					<tr>
						<th>${__("Tax Type")}</th>
						<th>${__("Period")}</th>
						<th style="text-align: right;">${__("Amount (AZN)")}</th>
						<th style="text-align: center;">${__("Status")}</th>
						<th>${__("Declaration")}</th>
						<th>${__("Payment")}</th>
					</tr>
				</thead>
				<tbody>
		`;

		for (const item of items) {
			const status_badge = get_status_badge(item.status);
			const amount_display = item.status === "Data Only" ? "—" : format_currency(item.tax_amount);
			html += `
				<tr>
					<td>${frappe.utils.escape_html(item.tax_type)}</td>
					<td>${frappe.utils.escape_html(item.sub_period || "")}</td>
					<td style="text-align: right; font-weight: bold;">${amount_display}</td>
					<td style="text-align: center;">${status_badge}</td>
					<td>${item.declaration_deadline || "—"}</td>
					<td>${item.payment_deadline || "—"}</td>
				</tr>
			`;
		}

		html += `
				<tr style="background: #d4edda; font-weight: bold;">
					<td colspan="2">${__("Total Tax Entries")}</td>
					<td style="text-align: right;">${format_currency(frm.doc.total_tax_amount)}</td>
					<td colspan="3"></td>
				</tr>
		`;

		if (frm.doc.total_payroll_taxes) {
			html += `
				<tr style="background: #d1ecf1;">
					<td colspan="2">${__("Payroll Taxes (collected data)")}</td>
					<td style="text-align: right;">${format_currency(frm.doc.total_payroll_taxes)}</td>
					<td colspan="3"></td>
				</tr>
			`;
		}

		html += `
				<tr style="background: #f8d7da; font-weight: bold; font-size: 14px;">
					<td colspan="2">${__("GRAND TOTAL TAX BURDEN")}</td>
					<td style="text-align: right;">${format_currency(frm.doc.grand_total_tax_burden)}</td>
					<td colspan="3"></td>
				</tr>
			</tbody></table>
		`;

		if (je_list.length) {
			html += `
				<h5 style="margin-top: 15px;">${__("Created Documents")}</h5>
				<table class="table table-sm table-bordered" style="font-size: 12px;">
					<thead style="background: #343a40; color: white;">
						<tr><th>${__("Journal Entry")}</th><th>${__("Tax Type")}</th><th>${__("Period")}</th><th style="text-align: right;">${__("Amount")}</th><th>${__("Date")}</th></tr>
					</thead><tbody>
			`;
			for (const je of je_list) {
				html += `
					<tr>
						<td><a href="/app/journal-entry/${je.journal_entry}">${je.journal_entry}</a></td>
						<td>${frappe.utils.escape_html(je.tax_type || "")}</td>
						<td>${frappe.utils.escape_html(je.sub_period || "")}</td>
						<td style="text-align: right;">${format_currency(je.amount)}</td>
						<td>${je.posting_date || ""}</td>
					</tr>
				`;
			}
			html += "</tbody></table>";
		}

		if (payroll.length) {
			html += `
				<h5 style="margin-top: 15px;">${__("Payroll Data (Reference Only)")}</h5>
				<table class="table table-sm table-bordered" style="font-size: 12px;">
					<thead style="background: #17a2b8; color: white;">
						<tr><th>${__("Component")}</th><th style="text-align: right;">${__("Amount")}</th><th>${__("Source")}</th></tr>
					</thead><tbody>
			`;
			for (const p of payroll) {
				html += `
					<tr>
						<td>${frappe.utils.escape_html(p.component || "")}</td>
						<td style="text-align: right;">${format_currency(p.amount)}</td>
						<td>${frappe.utils.escape_html(p.source || "")}</td>
					</tr>
				`;
			}
			html += "</tbody></table>";
		}

		html += '<div style="margin-top: 15px; padding: 12px; background: #fff3cd; border: 1px solid #ffc107; border-radius: 6px;">';
		html += `<h5 style="color: #856404; margin-bottom: 8px;">${__("Upcoming Deadlines")}</h5>`;
		for (const item of items) {
			if (item.enabled && item.declaration_deadline) {
				const decl_date = new Date(item.declaration_deadline);
				const today = new Date();
				const days_left = Math.ceil((decl_date - today) / (1000 * 60 * 60 * 24));
				const urgency = days_left <= 7 ? "color: #dc3545; font-weight: bold;" :
					days_left <= 30 ? "color: #e67e22;" : "color: #28a745;";

				html += `<div style="margin-bottom: 4px; ${urgency}">`;
				html += `${frappe.utils.escape_html(item.tax_type)} — `;
				html += `Declaration: ${item.declaration_deadline} | `;
				html += `Payment: ${item.payment_deadline || "N/A"}`;
				if (days_left <= 7) html += ` (${days_left} days left!)`;
				html += `</div>`;
			}
		}
		html += "</div></div>";

		frm.fields_dict.summary_html.$wrapper.html(html);
	},

	// ── Color Tax Items ───────────────────────────────────

	color_tax_items(frm) {
		setTimeout(() => {
			const status_bg = {
				"Entry Created": "#d4edda",
				"Calculated": "#d4edda",
				"Error": "#f8d7da",
				"Skipped": "#e2e3e5",
				"Data Only": "#d1ecf1",
				"Pending": "#fff3cd"
			};

			frm.$wrapper.find('.frappe-control[data-fieldname="tax_items"] .rows .row').each(function(i) {
				const item = (frm.doc.tax_items || [])[i];
				if (!item) return;
				const bg = status_bg[item.status];
				if (bg) $(this).css({ "background-color": bg, "transition": "background-color 0.3s" });
			});

			frm.$wrapper.find('.frappe-control[data-fieldname="entry_previews"] .rows .row').each(function(i) {
				const item = (frm.doc.entry_previews || [])[i];
				if (!item) return;
				const bg = {
					"Created": "#d4edda",
					"Failed": "#f8d7da",
					"Pending": "#fff3cd",
					"Existing": "#d4edda",
					"Difference": "#ffe0b2",
					"Skipped": "#e2e3e5"
				}[item.status];
				if (bg) $(this).css("background-color", bg);
			});

			frm.$wrapper.find('.frappe-control[data-fieldname="journal_entries"] .rows .row').each(function() {
				$(this).css("background-color", "#d4edda");
			});
		}, 300);
	}
});


// ── Helper Functions ──────────────────────────────────────

function get_status_badge(status) {
	const badges = {
		"Pending": `<span class="badge" style="background: #ffc107; color: #333;">${__("Pending")}</span>`,
		"Calculated": `<span class="badge" style="background: #17a2b8; color: white;">${__("Calculated")}</span>`,
		"Entry Created": `<span class="badge" style="background: #28a745; color: white;">${__("Created")}</span>`,
		"Existing": `<span class="badge" style="background: #28a745; color: white;">${__("Existing")}</span>`,
		"Difference": `<span class="badge" style="background: #fd7e14; color: white;">${__("Difference")}</span>`,
		"Data Only": `<span class="badge" style="background: #6c757d; color: white;">${__("Data Only")}</span>`,
		"Skipped": `<span class="badge" style="background: #adb5bd; color: white;">${__("Skipped")}</span>`,
		"Error": `<span class="badge" style="background: #dc3545; color: white;">${__("Error")}</span>`
	};
	return badges[status] || `<span class="badge badge-secondary">${status}</span>`;
}

function format_currency(val) {
	const num = parseFloat(val) || 0;
	return num.toLocaleString("az-AZ", {
		minimumFractionDigits: 2,
		maximumFractionDigits: 2
	}) + " AZN";
}
